﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Security.Cryptography;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Net;
using System.IO;
using System.IO.Compression;
using System.Text.RegularExpressions;
using System.Runtime.Serialization.Formatters.Binary;
using System.Xml;
using System.Threading;
using System.Linq.Expressions;


namespace MillionArthurTool
{
    public partial class Form1 : Form
    {
        private Log actionlog;
        private BingdingText logbind;
        private CardSet cardset;
        private cards allcards;
        private rewardbox Rewardbox;
        private cardchose CardChose;
        private List<BattleLog> Battles;
        private DataTable Battletable;
        private string DefaultUserAgent = "Million/235 (c1lgt; c1lgt; 4.1.2) samsung/c1lgt/c1lgt:4.1.2/JZO54K/E210LKLJME2:user/release-keys GooglePlay";

        private string szhost = "web.million-arthurs.com";
        private string szhostport = "web.million-arthurs.com";

        private string name = "";

        private string key0;
        private string key11;
        private string key12;
        private string baseKey;
        private string cardFull;
        private string cardMr;
        private string card3;
        private string lr3;
        private string card6;
        private string lr6;
        private string cardSUB;
        private string lrSUB;
        private string cardMaid;
        private string lrMaid;
        private string cardwolf;
        private string lrwolf;
        private string szFloor = "1";
        private string szActionLog = "";
        private string AreaName = "";
        private string szCharName = "";
        private string szSkill = "dummy";
        private string bname;
        private string labelgrk;
        private string labelgzg;
        private string labelzzg;
        private string labelzrg;
        private string labelzrk;
        private string labelxzg;
        private string labelxrg;
        private string labelxrk;
        private string szcookie;
        private string szCookie;
        private int BC = 0;
        private int MaxBc = 0;
        private int AP = 0;
        private int MaxAP = 0;
        private int iNowUserid = 0;
        private int iPartyid = 0;
        private int iSellPrice = 600;
        private int iAreaID = 0;
        private int LoginType = 1;
        private int ilowap = 1;
        private int iCardNum = 0;
        private int iGuildID = 0;
        private int master_boss_id;
        private int serial_id;
        private int lv;
        private int hp;
        private int hp_max;
        private int iJobID = 0;
        private int iSubBossID = 0;
        private int iContribution = 0;
        private int iContribution2 = 0;
        private bool bWinner = false;
        private bool bAutoChange = false;
        private bool bliqu = true;
        private bool bBonus = false;
        private bool bSub = false;

        private bool bActNoLimit = false;
        private bool bNoLimitedBC = false;
        private bool bxiap = false;

        private bool bThreadMain = false;
        private bool bThreadRank = false;
        private bool bThreadAttack = false;
        private bool bThreadExplore = false;
        private bool bThreadRigist = false;

        private bool bAttack = false;

        private XmlDocument areaxml;
        private XmlNodeList cardlist;

        private Thread MainThread;
        private Thread RankThread;
        private Thread AttackThread;
        private Thread ExploreThread;
        private Thread ExThread;
        private Thread RigistThread;


        private bool bLogin = false;

        public event EventHandler<EventArgs> AttackEvent;
        public event EventHandler<EventArgs> AttackEventEx;
        public event EventHandler<EventArgs> ExploreEvent;
        public event EventHandler<EventArgs> LoginEvent;
        public event EventHandler<EventArgs> MapsEvent;
        public event EventHandler<EventArgs> RewardsEvent;

        List<playerrank> ranklist = new List<playerrank>();
        bool bAting = false;
        int oldlv = 0;
        int[] cardc = { 0, 0 };
        void AttackMethod(object sender, EventArgs e)
        {
            bAting = true;
            if (iServer == 0)
            {

                
                int ilowbc = 2;
                int ire = 0;
                try
                {
                    ilowbc = int.Parse(textBox5.Text);
                }
                catch (System.Exception ex)
                {

                }
                if (BC >= ilowbc) getGuildFairyIfo();
                else if (radioButton4.Checked)
                {
                    useitem(2);
                    if (BC > ilowbc) getGuildFairyIfo();
                }
                else if (radioButton5.Checked)
                {
                    useitem(111);
                    if (BC > ilowbc) getGuildFairyIfo();
                }
                else
                {
                    getGuildFairyIfo();
                }
//                 if (iGuildID != 0 && serial_id != 0 && !bSub && BC >= ilowbc)
//                 {
//                     ChangeCard(CardChose.ibase3cardnum);
//                     if (!checkBox4.Checked)
//                     {
//                         if (lv < 100)
//                         {
//                             if (ichose != 3)
//                             {
//                                 ichose = 3;
//                                 changejob(ichose);
//                             }
//                         }
//                         else
//                         {
//                             if (ichose != 4)
//                             {
//                                 ichose = 4;
//                                 changejob(ichose);
//                             }
//                         }
//                     }
//                     ire = AtacktONE(iGuildID, serial_id);
//                     if (ire == 2)
//                     {
//                         AttackMethod(this, e);
//                     }
//                 }
//                 else if (iGuildID != 0 && serial_id != 0 && bSub && checkBox3.Checked && BC >= 2)
//                 {
//                     changejob(2);
//                     ChangeCard(CardChose.iwolfmusumecardnum);
//                     ire = AtacktONE(iGuildID, serial_id);
//                     changejob(bAutojob ? iJobID : ichose);
//                     if (ire == 2)
//                     {
//                         AttackMethod(this, e);
//                     }
//                 }
//                 else if (iGuildID != 0 && serial_id != 0 && bSub && !checkBox3.Checked && BC >= ilowbc)
//                 {
//                     getGuidIFO();
//                     if (iGuildID != 0 && serial_id != 0 && !bSub && BC >= ilowbc)
//                     {
//                         ChangeCard(CardChose.ibase3cardnum);
//                         ire = AtacktONE(iGuildID, serial_id);
//                         if (ire == 2)
//                         {
//                             AttackMethod(this, e);
//                         }
//                     }
//                     else if (iGuildID != 0 && serial_id != 0 && bSub && checkBox3.Checked && BC >= 2)
//                     {
//                         changejob(2);
//                         ChangeCard(CardChose.iwolfmusumecardnum);
//                         ire = AtacktONE(iGuildID, serial_id);
//                         changejob(bAutojob ? iJobID : ichose);
//                         if (ire == 2)
//                         {
//                             AttackMethod(this, e);
//                         }
//                     }
//                 }
//                 else if (iGuildID != 0 && serial_id != 0 && BC < ilowbc)
//                 {
//                     if (radioButton4.Checked)
//                     {
//                         useitem(2);
//                         ChangeCard(CardChose.ibase3cardnum);
//                         if (BC > ilowbc) ire = AtacktONE(iGuildID, serial_id);
//                         if (ire == 2)
//                         {
//                             AttackMethod(this, e);
//                         }
//                     }
//                     else if (radioButton5.Checked)
//                     {
//                         useitem(111);
//                         ChangeCard(CardChose.ibase3cardnum);
//                         if (BC > ilowbc) ire = AtacktONE(iGuildID, serial_id);
//                         if (ire == 2)
//                         {
//                             AttackMethod(this, e);
//                         }
//                     }
//                     else
//                     {
//                         getapbc();
//                     }
//                 }
//                 else if (iGuildID == 0 || serial_id == 0)
//                 {
// 
//                     ire = getGuidIFO();
//                     if (ire != 2)
//                     {
//                         AttackMethod(this, e);
//                     }
//                 }
            }
            else if(iServer == 1)
            {
                int ilowbc = 2;
                try
                {
                    ilowbc = int.Parse(textBox5.Text);
                }
                catch (System.Exception ex)
                {

                }
                if (BC >= ilowbc) getFairyIfo();
                else if (radioButton4.Checked)
                {
                    useitem(2);
                    if (BC > ilowbc) getFairyIfo();
                }
                else if (radioButton5.Checked)
                {
                    useitem(111);
                    if (BC > ilowbc) getFairyIfo();
                }
                else
                {
                    getapbc();
                }
            }
            bAting = false;
        }
        bool bAttackSub = false;
        DateTime subTime = DateTime.Now;
        void AttackMethodEx(object sender, EventArgs e)
        {
            int ire = 0;
            bAting = true;
            int ilowbc = 2;
            try
            {
                ilowbc = int.Parse(textBox5.Text);
            }
            catch (System.Exception ex)
            {

            }

            ire = getGuidIFO();
            if (ire == 2)
            {
                ire = getGuidIFO();
            }
            if (ire == 1)
            {
                ire = getGuidIFO();
            }
            if (ire == 2)
            {
                bAting = false;
                return;
            }
            if (oldlv != lv)
            {
                cardc = CardChose.getDeckNum(lv);
                oldlv = lv;
            }
            if (bBonus)
            {
                if (bSub)
                {
                    bAttackSub = false;
                    ChangeCard(CardChose.isubcardnum);
                    int ioldid = serial_id;
                    Thread.Sleep(15000);
                    ire = getGuidIFO();
                    if (ire == 1)
                    {
                    }
                    if (ire != 2 && ioldid == serial_id)
                    {
                        GuildBattle(iGuildID, serial_id);
                    }
                }
                else
                {

                    bAttackSub = false;
                    ChangeCard(CardChose.ifullcardnum);
                    int ioldid = serial_id;
                    Thread.Sleep(15000);
                    ire = getGuidIFO();
                    if (ire == 1)
                    {
                    }
                    else if (ire != 2 && ioldid == serial_id)
                    {
                        GuildBattle(iGuildID, serial_id);
                    }
                }
            }
            else
            {
                if (bSub)
                {
                    if (BC > ilowbc)
                    {
                        if (ire != 2 && !bAttackSub)
                        {
                            ChangeCard(CardChose.iwolfmusumecardnum);
                            changejob(2);
                            GuildBattle(iGuildID, serial_id);
                            bAttackSub = true;
                            subTime = DateTime.Now;
                            changejob(bAutojob ? iJobID : ichose);
                        }
                        else if (ire != 2 && bAttackSub && (DateTime.Now - subTime).TotalMinutes >= 2)
                        {
                            if (BC > CardChose.ibase3cardcost)
                            {
                                ChangeCard(CardChose.ibase3cardnum);
                                GuildBattle(iGuildID, serial_id);
                            }
                        }
                    }
                }
                else
                {
                    bAttackSub = false;
                    if (ire != 2 && BC > cardc[1])
                    {
                        ChangeCard(cardc[0]);
                        GuildBattle(iGuildID, serial_id);
                    }
                }
            }
            bAting = false;
        }
        void ExploreMethod(object sender, EventArgs e)
        {
            button7.Enabled = false;
            int ire = getapbc();
            while (ire == 3) getapbc();
            if (AP >= ilowap) while (AP >= ilowap && 3 != explore()) ;
            else if (radioButton7.Checked)
            {
                useitem(1); while (AP >= ilowap && 3 != explore()) ;
            }
            else if (radioButton6.Checked)
            {
                useitem(101); while (AP >= ilowap && 3 != explore()) ;
            }


            button7.Enabled = true;
        }

        void MapsMethod(object sender, EventArgs e)
        {
            GetAreaIfo();
        }

        void LoginMethod(object sender, EventArgs e)
        {
            EnableLoint(!bLogin);
        }
        void RewardsMethod(object sender, EventArgs e)
        {
            try
            {
                iSellPrice = int.Parse(textBox4.Text);
            }
            catch (System.Exception ex)
            {

            }
            try
            {
                while (-1 != getRewardsAll()) ;
            }
            catch (System.Exception ex)
            {
                actionlog.Text += "[" + DateTime.Now.ToString() + "]" + ex.Message + "\r\n";
                actionlog.WriteInfo(ex.Message + "\r\n");
            }
            button5.Enabled = true;
        }
        public Form1()
        {
            InitializeComponent();
            bExplore = false;
            iMasterBossID = 0;
            AttackEvent += new EventHandler<EventArgs>(AttackMethod);
            AttackEventEx += new EventHandler<EventArgs>(AttackMethodEx);
            ExploreEvent += new EventHandler<EventArgs>(ExploreMethod);
            LoginEvent += new EventHandler<EventArgs>(LoginMethod);
            MapsEvent += new EventHandler<EventArgs>(MapsMethod);
            RewardsEvent += new EventHandler<EventArgs>(RewardsMethod);
            actionlog = Log.instance;
            GetApple();
            timer1.Interval = 1000;
            timer1.Start();
            switch (iServer)
            {
                case 1:
                    key0 = baseKey;
                    break;
                default:
                    key0 = baseKey + "0000000000000000";
                    break;
            }
        }
        int geturerrank(int iUser)
        {
            int iRank = 0;
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = szhost;
            cookies.Add(c);
            string ulr = "http://" + szhostport + "/connect/app/ranking/ranking_next?cyt=1";
            IDictionary<string, string> parameters = new Dictionary<string, string>()
                {
                    {"",""}
                };
            parameters.Clear();
            if (iNowUserid == 0)
            {
                iNowUserid = getuserid();
            }
            // area_id=PWB4JL4LM1oYO7VbS8W7YQ%3D%3D%0A&auto_build=aieM12Y9tyl65ZBPd6GyUg%3D%3D%0A&floor_id=dcGs4R%2B%2FFzSWUgTwaO5wag%3D%3D%0A
            parameters.Add("from", Encrypt(iUser.ToString(), key12));
            parameters.Add("ranktype_id", Encrypt("4", key12));

            XmlDocument xml = null;
            while (true)
                try
                {
                    xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                    break;
                }
                catch (System.Exception ex)
                {
                }
            if (xml != null&&xml.InnerText!="")
            {
                XmlNodeList xmllist = xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("ranking").SelectSingleNode("user_list").SelectNodes("user");
                iRank = int.Parse(xmllist[0].SelectSingleNode("rank").InnerText) - 1;
            }
            return iRank;
        }
        private int getXSparty()
        {
            int ipart = 0;
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = szhost;
            cookies.Add(c);
            string ulr = "http://" + szhostport + "/connect/app/guild/guild_member_list?cyt=1";
            IDictionary<string, string> parameters = new Dictionary<string, string>()
                {
                    {"",""}
                };
            parameters.Clear();
            if (iNowUserid == 0)
            {
                iNowUserid = getuserid();
            }
            // area_id=PWB4JL4LM1oYO7VbS8W7YQ%3D%3D%0A&auto_build=aieM12Y9tyl65ZBPd6GyUg%3D%3D%0A&floor_id=dcGs4R%2B%2FFzSWUgTwaO5wag%3D%3D%0A
            parameters.Add("guild_member_type", Encrypt("1", key12));

            XmlDocument xml = null;
            while (true)
                try
                {
                    xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                    break;
                }
                catch (System.Exception ex)
                {
                }
            if (xml != null&&xml.InnerText!="")
            {
                XmlNodeList xmllist = xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("guild_member_list").SelectSingleNode("guild_party_list").SelectNodes("ex_party");
                int imaxPoint = 0; string szxsname = ""; string szxsleadername = "";
                foreach (XmlNode xmlparty in xmllist)
                {
                    int ipoint = int.Parse(xmlparty.SelectSingleNode("hunting_point").InnerText);
                    if (ipoint > imaxPoint)
                    {
                        imaxPoint = ipoint;
                        szxsname = xmlparty.SelectSingleNode("party").SelectSingleNode("name").InnerText;
                        szxsleadername = xmlparty.SelectSingleNode("party").SelectSingleNode("leader").SelectSingleNode("name").InnerText;
                        ipart = int.Parse(xmlparty.SelectSingleNode("party").SelectSingleNode("id").InnerText);

                    }

                }

                string szXrank = "对面团：" + szxsname + "，团长：" + szxsleadername + "贡献：" + imaxPoint + "/" + labelxzg + " | " + labelxrg + " | " + labelxrk + "\r\n\r\n";
                actionlog.Text += szXrank;
                partyrank(ipart);
            }
            return ipart;
        }
        private void partyrank(int iid)
        {
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = szhost;
            cookies.Add(c);
            string ulr = "http://" + szhostport + "/connect/app/party/party_only_member_list?cyt=1";
            IDictionary<string, string> parameters = new Dictionary<string, string>()
                {
                    {"",""}
                };
            parameters.Clear();
            // area_id=PWB4JL4LM1oYO7VbS8W7YQ%3D%3D%0A&auto_build=aieM12Y9tyl65ZBPd6GyUg%3D%3D%0A&floor_id=dcGs4R%2B%2FFzSWUgTwaO5wag%3D%3D%0A
            parameters.Add("pid", Encrypt(iid.ToString(), key12));

            XmlDocument xml = null;
            while (true)
                try
                {
                    xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                    break;
                }
                catch (System.Exception ex)
                {
                }
            if (xml != null&&xml.InnerText!="")
            {
                ranklist.Clear();
                XmlNodeList xmllist = xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("party_member_list").SelectNodes("member");
                int itotalrank = 0;
                foreach (XmlNode nodes in xmllist)
                {
                    playerrank rank1 = new playerrank();
                    int id = int.Parse(nodes.SelectSingleNode("id").InnerText);
                    rank1.name = nodes.SelectSingleNode("name").InnerText;
                    itotalrank += rank1.point = int.Parse(nodes.SelectSingleNode("guild_hunting_point").InnerText);
                    rank1.ilv = int.Parse(nodes.SelectSingleNode("town_level").InnerText);
                    rank1.logintime = nodes.SelectSingleNode("last_login").InnerText;
                    rank1.irank = geturerrank(id);
                    ranklist.Add(rank1);
                }
                ranklist.Sort();
                foreach (playerrank rank in ranklist)
                {
                    actionlog.Text += rank.ToString() + "\r\n";
                }
            }
        }
        private void partyrank()
        {
            button4.Enabled = false;
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = szhost;
            cookies.Add(c);
            string ulr = "http://" + szhostport + "/connect/app/party/party_only_member_list?cyt=1";
            IDictionary<string, string> parameters = new Dictionary<string, string>()
                {
                    {"",""}
                };
            parameters.Clear();
            // area_id=PWB4JL4LM1oYO7VbS8W7YQ%3D%3D%0A&auto_build=aieM12Y9tyl65ZBPd6GyUg%3D%3D%0A&floor_id=dcGs4R%2B%2FFzSWUgTwaO5wag%3D%3D%0A
            parameters.Add("pid", Encrypt(iPartyid.ToString(), key12));

            XmlDocument xml = null;
            while (true)
                try
                {
                    xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                    break;
                }
                catch (System.Exception ex)
                {
                }
            if (xml != null&&xml.InnerText!="")
            {
                FileStream sw = new FileStream("基佬排名.txt", FileMode.OpenOrCreate);
                ranklist.Clear();
                XmlNodeList xmllist = xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("party_member_list").SelectNodes("member");
                int itotalrank = 0;
                foreach (XmlNode nodes in xmllist)
                {
                    playerrank rank1 = new playerrank();
                    int id = int.Parse(nodes.SelectSingleNode("id").InnerText);
                    rank1.name = nodes.SelectSingleNode("name").InnerText;
                    itotalrank += rank1.point = int.Parse(nodes.SelectSingleNode("guild_hunting_point").InnerText);
                    rank1.ilv = int.Parse(nodes.SelectSingleNode("town_level").InnerText);
                    rank1.logintime = nodes.SelectSingleNode("last_login").InnerText;
                    rank1.irank = geturerrank(id);
                    ranklist.Add(rank1);
                }
                getRankINFO();
                string szGrank = "团贡 ：" + itotalrank.ToString() + "/" + labelzzg + "，日贡：" + labelzrg + "，团排：" + labelzrk + "\r\n";
                ranklist.Sort();
                foreach (playerrank rank in ranklist)
                {
                    byte[] ay = UTF8Encoding.UTF8.GetBytes(rank.ToString());
                    sw.Write(ay, 0, ay.Length);
                    sw.Flush();
                    actionlog.Text += rank.ToString() + "\r\n";
                }
                actionlog.Text += szGrank;
                sw.Close();

                getXSparty();
            }
            button4.Enabled = true;
        }
        private bool Login()
        {
            bool bReturn = false;
            string user = textBox1.Text;
            bool blimited = Properties.Settings.Default.userlimited;
            
            if (LoginType == 0 )
            {
                if (iServer == 0 && blimited)
                {
                    if (!userlist.Contains(user))
                    {
                        return false;
                    }
                }
                selectKey(user);
                string str = textBox2.Text;
                CookieCollection cookies = new CookieCollection();
                Cookie c = new Cookie("S", "");
                c.Domain = szhost;
                //cookies.Add(c);
                string ulr = "http://" + szhostport + "/connect/app/login?cyt=1";
                IDictionary<string, string> parameters = new Dictionary<string, string>()
                {
                    {"",""}
                };
                parameters.Clear();
                parameters.Add("login_id", Encrypt(user, key0));
                parameters.Add("password", Encrypt(str, key0));

                XmlDocument xml = null;
                while (true)
                    try
                    {
                        xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                        break;
                    }
                    catch (System.Exception ex)
                    {
                    }
                if (xml != null&&xml.InnerText!="")
                {

                    if (int.Parse(xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("code").InnerText) != 0)
                    {
                        string szlogtemp = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("message").InnerText + "\r\n";
                        actionlog.Text += "[" + DateTime.Now.ToString() + "]" + szlogtemp; actionlog.WriteInfo(szlogtemp);
                    }
                    else
                    {
                        szCookie = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("session_id").InnerText;

                        XmlNode node0 = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("your_data"); szCharName = node0.SelectSingleNode("name").InnerText;
                        XmlNode nodeBC = node0.SelectSingleNode("bc");
                        BC = int.Parse(nodeBC.SelectSingleNode("current").InnerText);
                        MaxBc = int.Parse(nodeBC.SelectSingleNode("max").InnerText);
                        XmlNode nodeAP = node0.SelectSingleNode("ap");
                        AP = int.Parse(nodeAP.SelectSingleNode("current").InnerText);
                        MaxAP = int.Parse(nodeAP.SelectSingleNode("max").InnerText);
                        cardlist = node0.SelectSingleNode("owner_card_list").SelectNodes("user_card");
                        XmlNodeList itemlist = node0.SelectNodes("itemlist");
                        if (itemlist != null)
                        {
                            foreach (XmlNode nodeitem in itemlist)
                            {
                                int id = int.Parse(nodeitem.SelectSingleNode("item_id").InnerText);
                                if (id == 202)
                                {
                                    iGuildItemCount = int.Parse(nodeitem.SelectSingleNode("num").InnerText);
                                }
                            }
                        }
                        if (iServer == 0) iPartyid = int.Parse(node0.SelectSingleNode("party_id").InnerText);
                        iuserLevel = int.Parse(node0.SelectSingleNode("town_level").InnerText);
                        try
                        {
                            XmlNode node1 = xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("login").SelectSingleNode("user_id");
                            iNowUserid = int.Parse(node1.InnerText);
                        }
                        catch (System.Exception ex)
                        {
                            iNowUserid = getuserid();
                        }
                        while (iNowUserid == 0)
                            iNowUserid = getuserid();
                        actionlog.Text += "登录成功\r\ncookie:" + szCookie + "|user:" + iNowUserid.ToString() + "|name:" + szCharName + "\r\n";
                        //actionlog.Text = szActionLog;
                        bReturn = true;
                    }
                }
            }
            else
            {
                selectKey(user);
                if (iServer == 0 && blimited)
                {
                    if (!userlist.Contains(user))
                    {
                        return false;
                    }
                }
                szCookie = textBox3.Text;
                iNowUserid = getuserid();
                if (iNowUserid != 0)
                {
                    bReturn = true;
                }
                else
                {
                    actionlog.Text += "user/cookie不匹配或者cookie失效\r\n";
                }
            }
            return bReturn;
        }
        private void threadMain()
        {
            actionlog.Text += "开始登陆\r\n";
            radioButton8.Enabled = false;
            radioButton10.Enabled = false;
            if (!Login())
            {
                LoginEvent.BeginInvoke(null, EventArgs.Empty, null, null);
                return;
            }
            bThreadMain = true;
            bLogin = true;
            //             RankThread = new Thread(threadRank);
            //             RankThread.Start();
            //             actionlog.Text += "开启rank监视\r\n";
            button3.Enabled = true;
            button4.Enabled = true;
            button5.Enabled = true;
            button7.Enabled = true;
            button9.Enabled = true;
            button10.Enabled = true;
            button11.Enabled = true;
            button12.Enabled = true;
            button13.Enabled = true;
            button14.Enabled = true;
            button15.Enabled = true;
            button16.Enabled = true;
            button17.Enabled = true;
            button18.Enabled = true;
            button20.Enabled = true;
            button21.Enabled = true;
            button22.Enabled = true;
            button23.Enabled = true;
            button24.Enabled = true;
            button25.Enabled = true;
            button26.Enabled = true;
            button27.Enabled = true;
            button28.Enabled = true;
            GetAreaIfo();
            button6.Enabled = true;
            if (iServer == 0)
            {
                UpdateJob();
            }
            button8.Enabled = true;
            //while (bThreadMain)
            //{
            //    int ilowbc = 2;
            //    try
            //    {
            //        ilowbc = int.Parse(textBox5.Text);
            //    }
            //    catch (System.Exception ex)
            //    {

            //    }
            //    while (!bThreadAttack) Thread.Sleep(1000);
            //    //if (BC < ilowbc) getapbc();
            //    //if (serial_id == 0) getGuidIFO();
            //    Thread.Sleep(1000);
            //}
        }
        private void threadRank()
        {
            while (bThreadRank)
            {
                getRankINFO();
                Thread.Sleep(30000);
            }
        }
        private void threadAttackEX()
        {
            while (bThreadAttack)
            {
                if (!bAting) AttackEventEx.BeginInvoke(null, EventArgs.Empty, null, null);
                Thread.Sleep(12000);
            }
        }
        private void threadAttack()
        {
            while (bThreadAttack)
            {
                if (!bAting) AttackEvent.BeginInvoke(null, EventArgs.Empty, null, null);
                Thread.Sleep(12000);
            }
        }
        int ioldre = 0;
        DateTime dtOld, dtnew;
        bool bThreadEx = false;
        private void ThreadEX()
        {
            int ire = getapbc();
            int ilowAP = 0;
            dtOld = DateTime.Now;
            while (bThreadEx)
            {
                if (DateTime.Now.Hour > 0 && DateTime.Now.Hour < 4)
                {
                    itestjob = 1;
                    iJobID = 0;
                    serial_id = 0;
                    Thread.Sleep(1000);
                    continue;
                }
                try
                {
                    ilowAP = int.Parse(textBox6.Text);
                }
                catch (System.Exception ex)
                {

                }
                if (ire != 3)
                {
                    ioldre = 0;
                    if (AP >= ilowap) ire = explore();
                    else ire = getapbc();

                }
                else if (AP >= ilowap && AP >= ilowAP)
                {
                    ire = explore();
                }
                else if (radioButton7.Checked)
                {
                    useitem(1);
                    if (AP >= ilowap && AP >= ilowAP) ire = explore();
                    else ire = getapbc();
                }
                else if (radioButton6.Checked)
                {
                    useitem(101);
                    if (AP >= ilowap && AP >= ilowAP) ire = explore();
                    else ire = getapbc();
                }
                else
                {
                    ire = getapbc();
                }
                if (ire == 65)
                {
                    while (bAting) Thread.Sleep(1000);
                    ioldre = 1;
                    AttackEventEx.BeginInvoke(null, EventArgs.Empty, null, null);
                    ire = 3;
                }
                else if (ire == 3)
                {

                    if (!bAting && (BC > cardc[1] || ioldre == 0) && (DateTime.Now - dtOld).TotalSeconds > 15)
                    {
                        ioldre = 1;
                        AttackEventEx.BeginInvoke(null, EventArgs.Empty, null, null);
                    }
                    else if (!bAting && (BC < cardc[1] || ioldre == 0) && (DateTime.Now - dtOld).TotalSeconds > 15)
                    {
                        if (radioButton4.Checked)
                        {
                            useitem(2);
                            AttackEventEx.BeginInvoke(null, EventArgs.Empty, null, null);
                        }
                        else if (radioButton5.Checked)
                        {
                            useitem(111);
                            AttackEventEx.BeginInvoke(null, EventArgs.Empty, null, null);
                        }
                    }
                }
            }
        }

        private void threadExplore()
        {
            if (iServer == 1)
            {
                int ire = getapbc();
                int ilowAP = 0;
                while (bThreadExplore)
                {
                    try
                    {
                        ilowAP = int.Parse(textBox6.Text);
                    }
                    catch (System.Exception ex)
                    {

                    }
                    if (bDM && BC > CardChose.ibase3cardcost)
                    {
                        GetAP();
                    }
                    if ((bDM && BC == MaxBc))
                    {
                        Thread.Sleep(1000);
                        ire = getapbc();
                    }
                    else if ((!bExplore ^ !checkBox6.Checked) && AP != MaxAP && !bDM)
                    {
                        Thread.Sleep(1000);
                        ire = getapbc();
                    }
                    else if (AP >= ilowap && AP >= ilowAP)
                    {
                        ire = explore_1();
                        
                    }
                    else if (radioButton7.Checked)
                    {
                        useitem(1);
                        if (AP >= ilowap && AP >= ilowAP) ire = explore_1();
                    }
                    else if (radioButton6.Checked)
                    {
                        useitem(101);
                        if (AP >= ilowap && AP >= ilowAP) ire = explore_1();
                    }
                    else if (bDM && BC > CardChose.ibase3cardcost)
                    {
                        GetAP();
                    }
                    else
                    {
                        Thread.Sleep(60000);
                        ire = getapbc();
                    }
                }
            }
            else
            {
                int ire = getapbc();
                int ilowAP = 0;
                while (bThreadExplore)
                {
                    try
                    {
                        ilowAP = int.Parse(textBox6.Text);
                    }
                    catch (System.Exception ex)
                    {

                    } 
                    if (radioButton9.Checked  && AP >= ilowap && AP >= ilowAP)
                    {

                        ire = explore();
                        fairygood(attackers, iAreaID);

                    }
                    else
                    if ((!bExplore /*^ !checkBox6.Checked*/) && AP != MaxAP)
                    {
                        Thread.Sleep(15000);
                        ire = getapbc();
                    }
                    else 
                    if (AP >= ilowap && AP >= ilowAP)
                    {
                        ire = explore();
                        //Thread.Sleep(10000);
                    }
                    else if (radioButton7.Checked)
                    {
                        useitem(1);
                        if (AP >= ilowap && AP >= ilowAP) ire = explore();
                    }
                    else if (radioButton6.Checked)
                    {
                        useitem(101);
                        if (AP >= ilowap && AP >= ilowAP) ire = explore();
                    }
                    else 
                    {
                        Thread.Sleep(60000);
                        ire = getapbc();
                    }
                }
            }
        }
        private void GetApple()
        {
            switch (iServer)
            {
                case 1:

                    baseKey = "rBwj1MIAivVN222b";
                    break;
                default:

                    baseKey = "uH9JF2cHf6OppaC1";
                    break;
            }
        }
        private void selectKey(string userName)
        {
            switch (iServer)
            {
                case 1:
                    key12 = baseKey;
                    break;
                default:

                    key12 = baseKey + userName;
                    for (int i = key12.Length; i < 32; i++)
                    {
                        key12 += "0";
                    }
                    break;
            }
        }
        public string Encrypt(string toEstr, string key)
        {
            string returnstr;
            byte[] toEstrArray = UTF8Encoding.UTF8.GetBytes(toEstr);
            byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key);
            AesManaged algorithm = new AesManaged
            {
                Padding = PaddingMode.PKCS7,
                Mode = CipherMode.ECB,
                Key = keyArray
            };
            ICryptoTransform cTransform = algorithm.CreateEncryptor();
            try
            {
                byte[] resultArray = cTransform.TransformFinalBlock(toEstrArray, 0, toEstrArray.Length);
                returnstr = Convert.ToBase64String(resultArray, 0, resultArray.Length);
            }
            catch (CryptographicException ex)
            {
                returnstr = ex.Message;
            }


            return returnstr;
        }
        public string Encrypt(byte[] toEstrArray, string key)
        {
            string returnstr;
            byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key);
            AesManaged algorithm = new AesManaged
            {
                Padding = PaddingMode.None,
                Mode = CipherMode.ECB,
                Key = keyArray
            };
            ICryptoTransform cTransform = algorithm.CreateEncryptor();
            try
            {
                byte[] resultArray = cTransform.TransformFinalBlock(toEstrArray, 0, toEstrArray.Length);
                returnstr = Convert.ToBase64String(resultArray, 0, resultArray.Length);
            }
            catch (CryptographicException ex)
            {
                returnstr = ex.Message;
            }


            return returnstr;
        }
        public string Decrypt(string toDstr, string key)
        {
            string returnstr;
            byte[] toDstrArray = Convert.FromBase64String(toDstr);
            returnstr = Decrypt(toDstrArray, key);
            return returnstr;
        }
        public string Decrypt2(string toDstr, string key)
        {
            string returnstr;
            byte[] toDstrArray = Convert.FromBase64String(toDstr);
            returnstr = Decrypt(toDstrArray, key);
            return returnstr;
        }
        public string Decrypt(byte[] toDstrArray, string key)
        {
            string returnstr;
            byte[] keyArray = Encoding.UTF8.GetBytes(key);
            AesManaged algorithm = new AesManaged
            {
                Padding = PaddingMode.PKCS7,
                Mode = CipherMode.ECB,
                Key = keyArray
            };
            int idefo = algorithm.BlockSize;
            ICryptoTransform cTransform = algorithm.CreateDecryptor();
            try
            {
                byte[] resultArray = cTransform.TransformFinalBlock(toDstrArray, 0, toDstrArray.Length);
                returnstr = Encoding.UTF8.GetString(resultArray);
            }
            catch (CryptographicException ex)
            {
                returnstr = ex.Message;
            }
            return returnstr;
        }
        public byte[] DecryptB(byte[] toDstrArray, string key, int i)
        {
            string returnstr;
            byte[] resultArray = null;
            byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key);
            AesManaged algorithm = new AesManaged
            {
                Padding = PaddingMode.None,
                Mode = CipherMode.ECB,
                Key = keyArray
            };
            ICryptoTransform cTransform = algorithm.CreateDecryptor();
            try
            {
                resultArray = cTransform.TransformFinalBlock(toDstrArray, 0, i);
                //returnstr = UTF8Encoding.UTF8.GetString(resultArray);
            }
            catch (CryptographicException ex)
            {
                returnstr = ex.Message;
            }
            return resultArray;
        }
        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true; //总是接受  
        }
        bool blogining = false;
        /// <summary>  
        /// 创建POST方式的HTTP请求  
        /// </summary>  
        /// <param name="url">请求的URL</param>  
        /// <param name="parameters">随同请求POST的参数名称及参数值字典</param>  
        /// <param name="timeout">请求的超时时间</param>  
        /// <param name="userAgent">请求的客户端浏览器信息，可以为空</param>  
        /// <param name="requestEncoding">发送HTTP请求时所用的编码</param>  
        /// <param name="cookies">随同HTTP请求发送的Cookie信息，如果不需要身份验证可以为空</param>  
        /// <returns>解码后的XML</returns>  
        public XmlDocument CreatePostHttpResponse(string url, IDictionary<string, string> parameters, int? timeout, string userAgent, Encoding requestEncoding, CookieCollection cookies)
        {
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException("url");
            }
            Encoding ec;
            if (requestEncoding == null)
            {
                ec = Encoding.Default;
            }
            else
            {
                ec = requestEncoding;
            }
            HttpWebRequest request = null;
            //如果是发送HTTPS请求  
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                request = WebRequest.Create(url) as HttpWebRequest;
                request.ProtocolVersion = HttpVersion.Version11;
            }
            else
            {
                request = WebRequest.Create(url) as HttpWebRequest;
                request.ProtocolVersion = HttpVersion.Version11;
            }
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ServicePoint.Expect100Continue = false;
            if (!string.IsNullOrEmpty(userAgent))
            {
                request.UserAgent = userAgent;
            }
            else
            {
                request.UserAgent = DefaultUserAgent;
            }
            request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
            request.KeepAlive = true;
            if (timeout.HasValue)
            {
                request.Timeout = timeout.Value;
            }
            if (cookies != null)
            {
                request.CookieContainer = new CookieContainer();
                request.CookieContainer.Add(cookies);
            }
            request.Expect = null;
            StringBuilder buffer = new StringBuilder();
            //如果需要POST数据  
            if (!(parameters == null || parameters.Count == 0))
            {
                int i = 0;
                foreach (string key in parameters.Keys)
                {
                    string str = parameters[key].Replace("=", "%3D");
                    str = str.Replace("+", "%2B");
                    str = str.Replace("/", "%2F");
                    if (str.Substring(str.Length - 3) != "%0A")
                    {
                        if (i > 0)
                        {
                            buffer.AppendFormat("&{0}={1}%0A", key, str);
                        }
                        else
                        {
                            buffer.AppendFormat("{0}={1}%0A", key, str);
                        }
                    }
                    else
                    {
                        if (i > 0)
                        {
                            buffer.AppendFormat("&{0}={1}", key, str);
                        }
                        else
                        {
                            buffer.AppendFormat("{0}={1}", key, str);
                        }
                    }
                    i++;
                }

            }
            byte[] data = ec.GetBytes(buffer.ToString());
            using (Stream stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }
            {
                XmlDocument XML1 = new XmlDocument();
                HttpWebResponse hwr = null;
                try
                {
                    hwr = request.GetResponse() as HttpWebResponse; 
                }
                catch (System.Exception ex)
                {
                    return XML1;
                }
                if (hwr == null)
                {
                    return XML1;
                }
                Stream st = hwr.GetResponseStream();
                int ilenth = (int)hwr.ContentLength;
                data = null;
                int c1 = 1024 * 400;
                if (ilenth < 0)
                {
                    data = new byte[c1];
                    MemoryStream ms = new MemoryStream();
                    int l = st.Read(data, 0, c1);
                    while (l > 0)
                    {
                        ms.Write(data, 0, l);
                        l = st.Read(data, 0, c1);
                    }
                    data = ms.ToArray();
                    ms.Close();
                }
                else
                {
                    data = new byte[ilenth];
                    
                    int pos = 0;
                    while (ilenth > 0)
                    {
                        int l = st.Read(data, pos, ilenth);
                        pos += l;
                        ilenth -= l;
                    }
                }
                hwr.Close();


                try
                {
                    XML1.LoadXml(Decrypt(data, key12));
                }
                catch (System.Exception ex)
                {

                    try
                    {
                        XML1.LoadXml(Decrypt(data, key0));
                    }
                    catch (System.Exception ex1)
                    {

                    }
                }
                if (XML1 != null)
                {
                    XmlNode errornode = XML1.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error");
                    if (errornode.SelectSingleNode("code").InnerText == "9000")
                    {
                        actionlog.Text += "掉线\r\n";
                        if (LoginType == 0 && !blogining)
                        {
                            actionlog.Text += "自动重连\r\n";
                            blogining = true;
                            if (Login())
                            {
                            }
                            else
                            {
                                actionlog.Text += "失败\r\n";
                            }
                            Thread.Sleep(5000);

                            blogining = false;
                        }
                        return null;
                    }
                }

                //int idata = data.Length;
                //int ioffline = iServer == 0 ? 1424 : 1088;
                //try
                //{
                //    XML1 = new XmlDocument();
                //    if (idata == ioffline && url != "http://" + szhostport + "/connect/app/friend/remove_friend?cyt=1")
                //    {
                //        actionlog.Text += "掉线\r\n";
                //        if (LoginType == 0 && !blogining)
                //        {
                //            actionlog.Text += "自动重连\r\n";
                //            blogining = true;
                //            if (Login())
                //            {
                //            }
                //            else
                //            {
                //                actionlog.Text += "失败\r\n";
                //            }
                //            Thread.Sleep(5000);

                //            blogining = false;
                //        }
                //        return null;
                //    }

                //}
                //catch (System.Exception ex)
                //{

                //    return null;
                //}
                //if (url == "http://" + szhostport + "/connect/app/mainmenu?cyt=1" || url == "http://" + szhostport + "/connect/app/regist?cyt=1" || url == "http://" + szhostport + "/connect/app/tutorial/next?cyt=1" || url == "http://" + szhostport + "/connect/app/tutorial/save_character?cyt=1" || url == "http://" + szhostport + "/connect/app/login?cyt=1" || idata == ioffline)
                //{
                //    XML1.LoadXml(Decrypt(data, key0));
                //}
                ////else if (url == "http://" + szhostport + "/connect/app/friend/remove_friend?cyt=1" || url == "http://" + szhostport + "/connect/app/friend/add_friend?cyt=1")
                ////{
                ////    XML1.LoadXml(Decrypt(data, key11));
                ////}
                //else
                //    XML1.LoadXml(Decrypt(data, key12));
                return XML1;
            }
        }

        double dWin = 0;

        int iGuildItemCount = 0;
        int itestjob = 1;
        private int GuildBattle(int iG, int iS, string SK = "dummy")
        {
            int iRe = -1;
            //             while (ts.TotalSeconds < 12)
            //             {
            //                 ts = DateTime.Now - dtold1;
            //                 Thread.Sleep(1000);
            //             }
            IDictionary<string, string> parameters = new Dictionary<string, string>()
            {
                {"",""}
            };
            parameters.Clear();
            parameters.Add("guild_id", Encrypt(iG.ToString(), key12));
            parameters.Add("serial_id", Encrypt(iS.ToString(), key12));
            parameters.Add("spp_skill_serial", Encrypt(SK, key12));
            string ulr = "http://" + szhostport + "/connect/app/fairy/guild_fairy_battle?cyt=1";
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = szhost;
            cookies.Add(c);
            XmlDocument xml = null;

            while (true)
            {
                try
                {
                    xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                    break;
                }
                catch (System.Exception ex)
                {
                    return iRe;
                }
            }
            bWinner = false;
            if (xml != null&&xml.InnerText!="")
            {
                guildfairytime = DateTime.Now;
                if (Properties.Settings.Default.xmlsave)xml.Save("guildbattle.xml");
                string szlogtemp = "战斗：";
                try
                {
                    if (iJobID == 0 && itestjob < 9)
                    {
                        if (-2 != changejob(itestjob)) itestjob++;
                    }
                    szCookie = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("session_id").InnerText;
                    if (int.Parse(xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("code").InnerText) != 0)
                    {
                        szlogtemp += xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("message").InnerText + "\r\n";
                        actionlog.Text += "[" + DateTime.Now.ToString() + "]" + szlogtemp; actionlog.WriteInfo(szlogtemp);
                        iRe = 1001;
                        return iRe;
                    }
                    dtOld = DateTime.Now;
                    bBonus = false;
                    XmlNode node0 = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("your_data");//szCharName = node0.SelectSingleNode("name").InnerText + "正在挂机";
                    if (node0 == null)
                    {
                        node0 = xml.SelectSingleNode("response").SelectSingleNode("body");
                        string szName = node0.ChildNodes[0].Name;
                        if (szName == "guild_top" || szName == "guild_defeat_event")
                        {
                            XmlNode node1 = node0.SelectSingleNode(szName).SelectSingleNode("guild_top_update");
                            XmlNode nodd3 = node1.SelectSingleNode("guild_reward_list");
                            if (nodd3 != null && szName == "guild_top")
                            {
                                bBonus = true;
                                string szBX = "";
                                int ibx = int.Parse(nodd3.SelectSingleNode("reward_box_list").SelectSingleNode("box_type").InnerText);
                                switch (ibx)
                                {
                                    case 10101:
                                        szBX = "白金箱";
                                        break;
                                    case 10102:
                                        szBX = "金箱";
                                        break;
                                    case 10103:
                                        szBX = "银箱";
                                        break;
                                    case 10104:
                                        szBX = "铜箱";
                                        break;
                                    case 10105:
                                        szBX = "木箱";
                                        break;
                                }
                                int ibxn = int.Parse(nodd3.SelectSingleNode("reward_box_list").SelectSingleNode("box_num").InnerText);
                                actionlog.Text += "[" + DateTime.Now.ToString() + "]" + "发现强敌：获得" + szBX + "*" + ibxn.ToString() + "\r\n";
                                actionlog.WriteInfo("发现强敌：获得" + szBX + "*" + ibxn.ToString() + "\r\n");
                            }
                            else if (szName == "guild_defeat_event")
                            {
                                nodd3 = node0.SelectSingleNode(szName).SelectSingleNode("guild_reward_list");
                                if (nodd3.SelectSingleNode("reward_box_list") != null)
                                {
                                    string szBX = "";
                                    int ibx = int.Parse(nodd3.SelectSingleNode("reward_box_list").SelectSingleNode("box_type").InnerText);
                                    switch (ibx)
                                    {
                                        case 10101:
                                            szBX = "白金箱";
                                            break;
                                        case 10102:
                                            szBX = "金箱";
                                            break;
                                        case 10103:
                                            szBX = "银箱";
                                            break;
                                        case 10104:
                                            szBX = "铜箱";
                                            break;
                                        case 10105:
                                            szBX = "木箱";
                                            break;
                                    }
                                    int ibxn = int.Parse(nodd3.SelectSingleNode("reward_box_list").SelectSingleNode("box_num").InnerText);
                                    actionlog.Text += "[" + DateTime.Now.ToString() + "]" + nodd3 != null ? "强敌已死，获得" + szBX + "*" + ibxn.ToString() + "\r\n" : "强敌已死\r\n";
                                    actionlog.WriteInfo(nodd3 != null ? "强敌已死，获得" + szBX + "*" + ibxn.ToString() + "\r\n" : "强敌已死\r\n");
                                    serial_id = 0;
                                }
                                else
                                {
                                    actionlog.Text += "[" + DateTime.Now.ToString() + "]" + "强敌已死\r\n";
                                    actionlog.WriteInfo("强敌已死\r\n");
                                }
                            }
                            else
                            {
                                szlogtemp += "新怪\r\n";
                                bBonus = false;
                            }
                            XmlNode node2 = node1.SelectSingleNode("fairy");
                            XmlNode nodeweak = node1.SelectSingleNode("guild_fairy_weak");

                            if (nodeweak != null && bAutojob)
                            {
                                int iweakid = int.Parse(nodeweak.SelectSingleNode("id").InnerText);
                                if (iweakid != iJobID)
                                {
                                    if (-2 != changejob(iweakid)) iJobID = iweakid;
                                }
                            }
                            //master_boss_id = int.Parse(node2.SelectSingleNode("master_boss_id").InnerText);
                            XmlNodeList nodelogs = node1.SelectNodes("guild_log");
                            //                             szBattleLog = string.Empty;
                            //                             foreach (XmlNode nodes in nodelogs)
                            //                             {
                            //                                 szBattleLog += nodes.SelectSingleNode("log_time").InnerText + " - ";
                            //                                 szBattleLog += nodes.SelectSingleNode("user_name").InnerText + ":   ";
                            //                                 szBattleLog += nodes.SelectSingleNode("message").InnerText + "\r\n\r\n";
                            //                             }
                            serial_id = int.Parse(node2.SelectSingleNode("serial_id").InnerText);
                            lv = int.Parse(node2.SelectSingleNode("lv").InnerText);
                            hp = int.Parse(node2.SelectSingleNode("hp").InnerText);
                            hp_max = int.Parse(node2.SelectSingleNode("hp_max").InnerText);
                            bname = node2.SelectSingleNode("name").InnerText;
                            XmlNode nodef = node1.SelectSingleNode("force_gauge");
                            if (nodef != null)
                            {
                                int iOwn = int.Parse(nodef.SelectSingleNode("own").InnerText);
                                int iRival = int.Parse(nodef.SelectSingleNode("rival").InnerText);
                                int iTotal = int.Parse(nodef.SelectSingleNode("total").InnerText);
                                dWin = (double)(iOwn - iRival) / iTotal / 2;
                            }
                            iGuildID = int.Parse(node2.SelectSingleNode("discoverer_id").InnerText);
                            int timel = int.Parse(node2.SelectSingleNode("time_limit").InnerText);
                            if (node2.SelectSingleNode("master_boss_id") != null)
                            {
                                iRe = 0;
                                if (int.Parse(node2.SelectSingleNode("master_boss_id").InnerText) == iSubBossID)
                                    if (timel > 7080)
                                    {
                                        iRe = 3;
                                    }
                            }
                            else
                            {
                                if (timel > 7080)
                                {
                                    iRe = 3;
                                }
                            }
                            if (szName == "guild_defeat_event")
                            {
                                serial_id = 0;
                                iRe = 2;
                            }
                        }
                        else if (szName == "guild_fairy_event")
                        {
                            iRe = 1;
                        }
                        else if (szName == "guild_top_no_fairy")
                        {
                            iRe = 2;

                            iSubBossID = int.Parse(node0.SelectSingleNode("guild_top_no_fairy").SelectSingleNode("guild_boss").SelectSingleNode("sub_boss_id").InnerText);
                            hp = 0;
                            serial_id = 0;
                        }
                        return iRe;
                    }
                    XmlNode nodeBC = node0.SelectSingleNode("bc");
                    XmlNodeList itemlist = node0.SelectNodes("itemlist");
                    if (itemlist!=null)
                    {
                        foreach (XmlNode nodeitem in itemlist)
                        {
                            int id = int.Parse(nodeitem.SelectSingleNode("item_id").InnerText);
                            if (id == 202)
                            {
                                iGuildItemCount = int.Parse(nodeitem.SelectSingleNode("num").InnerText);
                            }
                        }
                    }
                    BC = int.Parse(nodeBC.SelectSingleNode("current").InnerText);
                    MaxBc = int.Parse(nodeBC.SelectSingleNode("max").InnerText);
                    XmlNode nodeAP = node0.SelectSingleNode("ap");
                    AP = int.Parse(nodeAP.SelectSingleNode("current").InnerText);
                    MaxAP = int.Parse(nodeAP.SelectSingleNode("max").InnerText);
                    iContribution = int.Parse(xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("own_fairy_battle_result").SelectSingleNode("contribution_info").SelectSingleNode("hp_contribution").InnerText);
                    iContribution2 = int.Parse(xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("own_fairy_battle_result").SelectSingleNode("contribution_info").SelectSingleNode("battle_contribution").InnerText);
                    bWinner = int.Parse(xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("own_fairy_battle_result").SelectSingleNode("winner").InnerText) == 1;
                    iRe = 0;
                    BattleLog bl = new BattleLog(xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("battle_battle"), lv, iContribution, iContribution2);
                    Battles.Add(bl);
                    listBox1.Items.Add(bl);
                    listBox1.DisplayMember = "Text";
                    listBox1.ValueMember = "Value";
                    if (bWinner)
                    {
                        szlogtemp += "-战斗胜利-";
                    }
                    szlogtemp += "贡献：残血" + iContribution.ToString() + "战斗" + iContribution2.ToString();

                    XmlNodeList noddr = null;
                    try
                    {
                        noddr = xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("own_fairy_battle_result").SelectNodes("guild_reward_list");
                    }
                    catch (System.Exception ex)
                    {
                    }
                    if (noddr != null)
                    {
                        try
                        {
                            int iitemcount1 = int.Parse(noddr[0].SelectSingleNode("special_item").SelectSingleNode("before_count").InnerText);
                            int iitemcount2 = int.Parse(noddr[0].SelectSingleNode("special_item").SelectSingleNode("after_count").InnerText);


                            szlogtemp += "收集道具：" + (iitemcount2 - iitemcount1).ToString() + "/" + iitemcount2.ToString() + "\r\n";
                        }
                        catch (System.Exception ex)
                        {
                            szlogtemp += "\r\n";
                        }
                        if (noddr.Count > 1)
                        {
                            //bBonus = true;
                            string szBX = "";
                            int ibx = int.Parse(noddr[1].SelectSingleNode("reward_box_list").SelectSingleNode("box_type").InnerText);
                            switch (ibx)
                            {
                                case 10101:
                                    szBX = "白金箱";
                                    break;
                                case 10102:
                                    szBX = "金箱";
                                    break;
                                case 10103:
                                    szBX = "银箱";
                                    break;
                                case 10104:
                                    szBX = "铜箱";
                                    break;
                                case 10105:
                                    szBX = "木箱";
                                    break;
                            }
                            int ibxn = int.Parse(noddr[1].SelectSingleNode("reward_box_list").SelectSingleNode("box_num").InnerText);
                            szlogtemp += "杀死强敌：获得" + szBX + "*" + ibxn.ToString() + "\r\n";
                            serial_id = 0;
                        }
                    }
                    actionlog.Text += "[" + DateTime.Now.ToString() + "]" + szlogtemp; actionlog.WriteInfo(szlogtemp);

                }
                catch (System.Exception ex)
                {
                    szlogtemp += ex.Message + "\r\n";
                    actionlog.Text += "[" + DateTime.Now.ToString() + "]" + szlogtemp; actionlog.WriteInfo(szlogtemp);
                }
            }
            return iRe;

        }

        private void ThreadRigist()
        {
            bThreadRigist = true;
            if (bNoLimitedBC)
            {
                while (iNowUserid == 0)
                {
                    iNowUserid = getuserid();
                }
                while (bNoLimitedBC)
                {
                    try
                    {

                        string szPas = "";
                        Guid gu = Guid.NewGuid();

                        byte[] gdata = gu.ToByteArray();
                        if (szPas == "")
                        {
                            for (int j = 9; j < gdata.Length; j++)
                            {
                                szPas += Convert.ToString(gdata[j], 16);
                            }
                        }
                        string szusername = szPas;
                        szcookie = "";
                        try
                        {
                            key11 = baseKey + szusername.Substring(0, 16);
                        }
                        catch (System.Exception ex)
                        {

                            key11 = baseKey + szusername;
                        }
                        for (int i = key11.Length; i < 32; i++)
                        {
                            key11 += "0";
                        }
                        CookieCollection cookies = new CookieCollection();
                        Cookie c = new Cookie("S", szcookie);
                        c.Domain = szhost;
                        cookies.Add(c);
                        string ulr = "http://" + szhostport + "/connect/app/regist?cyt=1";
                        IDictionary<string, string> parameters = new Dictionary<string, string>()
                        {
                            {"",""}
                        };
                        parameters.Clear();
                        parameters.Add("login_id", Encrypt(szusername, key0));
                        parameters.Add("password", Encrypt(szPas, key0));
                        string sG = "";
                        for (int j = 8; j < gdata.Length; j++)
                        {
                            sG += Convert.ToString(gdata[j], 16);
                        }
                        parameters.Add("param", Encrypt(sG, key0));

                        XmlDocument xml = null;
                        while (true)
                            try
                            {
                                xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                                break;
                            }
                            catch (System.Exception ex)
                            {
                            }
                        if (int.Parse(xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("code").InnerText) != 0)
                        {
                            continue;
                        }
                        szcookie = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("session_id").InnerText;
                        int istep = 100;
                        string szNam = "";
                        c = new Cookie("S", szcookie);
                        c.Domain = szhost;
                        cookies.Add(c);

                        istep = 100;
                        szNam = "教程" + istep.ToString();
                        ulr = "http://" + szhostport + "/connect/app/tutorial/next?cyt=1";
                        parameters.Clear();
                        parameters.Add("S", Encrypt(szcookie, key0));
                        parameters.Add("step", Encrypt(istep.ToString(), key0));
                        try
                        {
                            xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);

                        }
                        catch (System.Exception ex)
                        {
                            continue;
                        }

                        istep = 7025;
                        szNam = "教程" + istep.ToString();
                        ulr = "http://" + szhostport + "/connect/app/tutorial/next?cyt=1";
                        parameters.Clear();
                        parameters.Add("S", Encrypt(szcookie, key0));
                        parameters.Add("step", Encrypt(istep.ToString(), key0));
                        try
                        {
                            xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);

                        }
                        catch (System.Exception ex)
                        {
                            continue;
                        }


                        istep = 8000;
                        szNam = "教程" + istep.ToString() + "教程完成";
                        parameters.Clear();
                        parameters.Add("S", Encrypt(szcookie, key0));
                        parameters.Add("step", Encrypt("8000", key0));

                        try
                        {
                            xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);

                        }
                        catch (System.Exception ex)
                        {
                            continue;
                        }

                        if (xml == null)
                        {
                            continue;
                        }

                        szcookie = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("session_id").InnerText;

                        XmlNode node1 = xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("login").SelectSingleNode("user_id");
                        int iUserid = int.Parse(node1.InnerText);


                        c = new Cookie("S", szcookie);
                        c.Domain = szhost;
                        cookies.Add(c);

                        ulr = "http://" + szhostport + "/connect/app/friend/add_friend?cyt=1";
                        while (true)
                            try
                            {
                                parameters.Clear();
                                parameters.Add("dialog", Encrypt("1", key11));
                                parameters.Add("user_id", Encrypt(iNowUserid.ToString(), key11));
                                xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                                break;
                            }
                            catch (System.Exception ex)
                            {
                            }


                        alowuser(iUserid);
                        setbc();

                        c = new Cookie("S", szcookie);
                        c.Domain = szhost;
                        cookies.Add(c);
                        int i2 = 0;
                        ulr = "http://" + szhostport + "/connect/app/friend/remove_friend?cyt=1";
                        while (true)
                            try
                            {
                                parameters.Clear();
                                parameters.Add("dialog", Encrypt("1", key11));
                                parameters.Add("user_id", Encrypt(iNowUserid.ToString(), key11));
                                xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                                break;
                            }
                            catch (System.Exception ex)
                            {
                                i2++;
                                if (i2 > 5)
                                {
                                    break;
                                }
                            }
                        bActNoLimit = false;
                    }
                    catch (System.Exception ex)
                    {

                    }
                }
            }
            bThreadRigist = true;
        }

        private int alowuser(int iuser)
        {
            string ulr = "http://" + szhostport + "/connect/app/friend/approve_friend?cyt=1";
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = szhost;
            cookies.Add(c);
            IDictionary<string, string> parameters = new Dictionary<string, string>()
                    {
                        {"",""}
                    };
            parameters.Clear();
            parameters.Add("dialog", Encrypt("1", key12));
            parameters.Add("user_id", Encrypt(iuser.ToString(), key12));

            XmlDocument xml = null;
            try
            {
                xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);

            }
            catch (System.Exception ex)
            {
                return -1;
            }
            if (xml != null&&xml.InnerText!="")
            {
                if (int.Parse(xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("code").InnerText) != 0)
                {
                    string errormessage = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("message").InnerText + "\r\n";
                    actionlog.Text += "[" + DateTime.Now.ToString() + "]" + errormessage;
                    return -1;
                }
                szCookie = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("session_id").InnerText;

            }
            return 0;
        }

        private void setbc()
        {
            string ulr = "http://" + szhostport + "/connect/app/town/pointsetting?cyt=1";
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = szhost;
            cookies.Add(c);
            IDictionary<string, string> parameters = new Dictionary<string, string>()
                    {
                        {"",""}
                    };
            parameters.Clear();
            if (bxiap)
            {
                parameters.Add("ap", Encrypt("3", key12));
                parameters.Add("bc", Encrypt("0", key12));
            }
            else
            {
                parameters.Add("ap", Encrypt("0", key12));
                parameters.Add("bc", Encrypt("3", key12));
            }

            XmlDocument xml = null;
            while (true)
                try
                {
                    xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                    break;
                }
                catch (System.Exception ex)
                {
                }
            if (xml != null&&xml.InnerText!="")
            {
                if (int.Parse(xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("code").InnerText) != 0)
                {
                    string errormessage = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("message").InnerText + "\r\n";
                    actionlog.Text += "[" + DateTime.Now.ToString() + "]" + errormessage;
                    return;
                }
                szCookie = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("session_id").InnerText;
                XmlNode node0 = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("your_data"); szCharName = node0.SelectSingleNode("name").InnerText + "正在挂机";

                XmlNode nodeBC = node0.SelectSingleNode("bc");
                BC = int.Parse(nodeBC.SelectSingleNode("current").InnerText);

                MaxBc = int.Parse(nodeBC.SelectSingleNode("max").InnerText);
                XmlNode nodeAP = node0.SelectSingleNode("ap");
                AP = int.Parse(nodeAP.SelectSingleNode("current").InnerText);
                MaxAP = int.Parse(nodeAP.SelectSingleNode("max").InnerText);
            }
        }
        private void fairygood2(List<int> user, int iserial)
        {
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = szhost;
            cookies.Add(c);
            IDictionary<string, string> parameters = new Dictionary<string, string>()
            {
                {"",""}
            };

            string struser = "";
            
                if (struser == "")
                {
                    struser += user[0].ToString();
                }
            

            parameters.Clear();

            parameters.Add("dialog", Encrypt("1", key12));
            parameters.Add("serial_id", Encrypt(struser, key12));
            parameters.Add("user_id", Encrypt(iserial.ToString(), key12));
            string ulr = "http://" + szhostport + "/connect/app/private_fairy/private_fairy_battle_good?cyt=1";
            XmlDocument xml = null;
            for (int i = 0; i < 20; i++)
            {
                try
                {
                    xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                    break;
                }
                catch (System.Exception ex)
                {
                    continue; ;
                }
            }
            try
            {
                if (Properties.Settings.Default.xmlsave) xml.Save("fairygood.xml");
                if (xml != null && xml.InnerText != "")
                {
                    if (int.Parse(xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("code").InnerText) != 0)
                    {
                        //                     if (bAutoChange)
                        //                     {
                        //                         iAreaID--;
                        //                         szFloor = "1";
                        //                         bAutoChange = false;
                        //                     }
                        //                     else
                        //                     {
                        //                         iAreaID = 0;
                        //                         szFloor = "1";
                        //                     }
                        return;
                    }
                    szCookie = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("session_id").InnerText;
                    XmlNode node0 = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("your_data"); szCharName = node0.SelectSingleNode("name").InnerText;

                    XmlNode nodeBC = node0.SelectSingleNode("bc");
                    BC = int.Parse(nodeBC.SelectSingleNode("current").InnerText);

                    MaxBc = int.Parse(nodeBC.SelectSingleNode("max").InnerText);
                    XmlNode nodeAP = node0.SelectSingleNode("ap");
                    AP = int.Parse(nodeAP.SelectSingleNode("current").InnerText);
                    MaxAP = int.Parse(nodeAP.SelectSingleNode("max").InnerText);
                    XmlNode node1 = xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("get_floor");
                    ilowap = int.Parse(node1.SelectSingleNode("floor_info").SelectSingleNode("cost").InnerText);
                    AreaName = node1.SelectSingleNode("area_name").InnerText;

                    XmlNode nodeg = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("guild_fairy_state");
                    int ire = 0;
                    if (nodeg != null)
                    {
                        ire = int.Parse(nodeg.SelectSingleNode("fairy_state").InnerText);
                    }
                }
            }
            catch (System.Exception ex)
            {
                //serial_id = 0;
            }
        }
        private void fairygood(List<int> user, int iserial)
        {
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = szhost;
            cookies.Add(c);
            IDictionary<string, string> parameters = new Dictionary<string, string>()
            {
                {"",""}
            };

            string struser = "";
            foreach (int us in user)
            {
                if (struser == "")
                {
                    struser += us.ToString();
                }
                else
                {
                    struser += "," + us.ToString();
                }
            }

            parameters.Clear();
            
            parameters.Add("dialog", Encrypt("1", key12));
            parameters.Add("serial_id", Encrypt(iserial.ToString(), key12));
            parameters.Add("user_id", Encrypt(struser, key12));
            string ulr = "http://" + szhostport + "/connect/app/private_fairy/private_fairy_battle_good?cyt=1";
            XmlDocument xml = null;
            for (int i = 0; i < 20;i++ )
            {
                try
                {
                    xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                    break;                    
                }
                catch (System.Exception ex)
                {
                    continue; ;
                }
            }
            try
            {
                if (Properties.Settings.Default.xmlsave) xml.Save("fairygood.xml");
                if (xml != null && xml.InnerText != "")
                {
                    if (int.Parse(xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("code").InnerText) != 0)
                    {
                        //                     if (bAutoChange)
                        //                     {
                        //                         iAreaID--;
                        //                         szFloor = "1";
                        //                         bAutoChange = false;
                        //                     }
                        //                     else
                        //                     {
                        //                         iAreaID = 0;
                        //                         szFloor = "1";
                        //                     }
                        return;
                    }
                    szCookie = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("session_id").InnerText;
                    XmlNode node0 = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("your_data"); szCharName = node0.SelectSingleNode("name").InnerText;

                    XmlNode nodeBC = node0.SelectSingleNode("bc");
                    BC = int.Parse(nodeBC.SelectSingleNode("current").InnerText);

                    MaxBc = int.Parse(nodeBC.SelectSingleNode("max").InnerText);
                    XmlNode nodeAP = node0.SelectSingleNode("ap");
                    AP = int.Parse(nodeAP.SelectSingleNode("current").InnerText);
                    MaxAP = int.Parse(nodeAP.SelectSingleNode("max").InnerText);
                    XmlNode node1 = xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("get_floor");
                    ilowap = int.Parse(node1.SelectSingleNode("floor_info").SelectSingleNode("cost").InnerText);
                    AreaName = node1.SelectSingleNode("area_name").InnerText;

                    XmlNode nodeg = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("guild_fairy_state");
                    int ire = 0;
                    if (nodeg != null)
                    {
                        ire = int.Parse(nodeg.SelectSingleNode("fairy_state").InnerText);
                    }
                }
            }
            catch (System.Exception ex)
            {
                //serial_id = 0;
            }
        }
        List<int> attackers = new List<int>();
        int igoodid = 0;        
        private void fairyhistory(int iuser, int iserial)
        {
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = szhost;
            cookies.Add(c);
            IDictionary<string, string> parameters = new Dictionary<string, string>()
            {
                {"",""}
            };
            parameters.Clear();
            parameters.Add("serial_id", Encrypt(iserial.ToString(), key12));
            parameters.Add("user_id", Encrypt(iuser.ToString(), key12));
            string ulr = "http://" + szhostport + "/connect/app/private_fairy/private_fairy_history?cyt=1";
            XmlDocument xml = null;
            while (true)
            {
                try
                {
                    xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                    break;
                }
                catch (System.Exception ex)
                {
                    continue; ;
                }
            }
            try
            {
                if (Properties.Settings.Default.xmlsave) xml.Save("fairyhistory.xml");
                XmlNode fairynode = xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("fairy_history").SelectSingleNode("fairy");
                string szBOSS = fairynode.SelectSingleNode("name").InnerText + "-lv" + fairynode.SelectSingleNode("lv").InnerText;
                XmlNodeList attackernodes = xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("fairy_history").SelectSingleNode("attacker_history").SelectNodes("attacker");
                string strnames = "";
                olda = attackers;
                
                attackers.Clear();
                foreach (XmlNode node in attackernodes)
                {
                    int iu = int.Parse(node.SelectSingleNode("user_id").InnerText);
                    if (iu != iuser)
                    {
                        attackers.Add(iu);
                        strnames += node.SelectSingleNode("user_name").InnerText + "|" + node.SelectSingleNode("attack_point").InnerText + "|" + node.SelectSingleNode("attack_times").InnerText+"; ";
                    }
                }
                actionlog.Text += szBOSS + " 应援感谢：" + strnames + "\r\n";
                fairygood(attackers, iserial);
                ioldgood = igoodid;
                igoodid = iserial;
            }
            catch (System.Exception ex)
            {
                //serial_id = 0;
            }
        }
        private void fairytop(int iuser,int iserial)
        {
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = szhost;
            cookies.Add(c); 
            IDictionary<string, string> parameters = new Dictionary<string, string>()
            {
                {"",""}
            };
            parameters.Clear();
            parameters.Add("serial_id", Encrypt(iserial.ToString(), key12));
            parameters.Add("user_id", Encrypt(iuser.ToString(), key12));
            string ulr = "http://" + szhostport + "/connect/app/private_fairy/private_fairy_top?cyt=1";
            XmlDocument xml = null;
            while (true)
            {
                try
                {
                    xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                    break;
                }
                catch (System.Exception ex)
                {
                    continue; ;
                }
            }
            try
            {
                if (Properties.Settings.Default.xmlsave)xml.Save("fairytop.xml");
               
            }
            catch (System.Exception ex)
            {
                //serial_id = 0;
            }
        }
        DateTime guildfairytime = DateTime.Now;
        private int guildfairybattle(int iU, int iS)
        {
            int iRe = -1;
            guildfairytime = DateTime.Now;
            //             while (ts.TotalSeconds < 12)
            //             {
            //                 ts = DateTime.Now - dtold1;
            //                 Thread.Sleep(1000);
            //             }
            int oldBC = BC;
            IDictionary<string, string> parameters = new Dictionary<string, string>()
            {
                {"",""}
            };
            parameters.Clear();
            parameters.Add("no", Encrypt("0", key12));
            parameters.Add("serial_id", Encrypt(iS.ToString(), key12));
            parameters.Add("user_id", Encrypt(iU.ToString(), key12));
            string ulr = "http://" + szhostport + "/connect/app/private_fairy/private_fairy_battle?cyt=1";
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = szhost;
            cookies.Add(c);
            XmlDocument xml = null;

            while (true)
            {
                try
                {
                    xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                    break;
                }
                catch (System.Exception ex)
                {
                    return iRe;
                }
            } 
            bWinner = false;
            if (xml != null&&xml.InnerText!="")
            {
                if (Properties.Settings.Default.xmlsave)xml.Save("fairybattle.xml");
                string szlogtemp = "战斗：";
                try
                {
                    szCookie = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("session_id").InnerText;
                    if (int.Parse(xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("code").InnerText) != 0)
                    {
                        szlogtemp += xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("message").InnerText + "\r\n";
                        szActionLog += "[" + DateTime.Now.ToString() + "]" + szlogtemp; actionlog.WriteInfo(szlogtemp);
                        iRe = 1001;
                        return iRe;
                    }

                    int iGuildItem = 0;
                    XmlNode node0 = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("your_data");//szCharName = node0.SelectSingleNode("name").InnerText + "正在挂机";
                    if (node0 != null)
                    {
                        XmlNode nodeBC = node0.SelectSingleNode("bc");
                        BC = int.Parse(nodeBC.SelectSingleNode("current").InnerText);
                        MaxBc = int.Parse(nodeBC.SelectSingleNode("max").InnerText);
                        XmlNode nodeAP = node0.SelectSingleNode("ap");
                        AP = int.Parse(nodeAP.SelectSingleNode("current").InnerText);
                        MaxAP = int.Parse(nodeAP.SelectSingleNode("max").InnerText);
                        szlogtemp += " BC:" + oldBC.ToString() + "->" + BC.ToString() + " ";


                        try
                        {
                            int exp1 = int.Parse(xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("battle_result").SelectSingleNode("before_exp").InnerText);
                            int exp2 = int.Parse(xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("battle_result").SelectSingleNode("after_exp").InnerText);
                            bWinner = int.Parse(xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("battle_result").SelectSingleNode("winner").InnerText) == 1;
                            szlogtemp += "经验" + exp1.ToString() + "->" + exp2.ToString();
                            iRe = 0;
                            XmlNodeList itemlist = node0.SelectNodes("itemlist");
                            if (itemlist != null)
                            {
                                foreach (XmlNode nodeitem in itemlist)
                                {
                                    int id = int.Parse(nodeitem.SelectSingleNode("item_id").InnerText);
                                    if (id == 202)
                                    {
                                        iGuildItem = int.Parse(nodeitem.SelectSingleNode("num").InnerText);
                                    }
                                }
                            }
                        }
                        catch (System.Exception ex)
                        {

                            szlogtemp += "强敌已死";
                        }
                    }

                    if (bWinner)
                    {
                        szlogtemp += "-战斗胜利-";
                    }

                    XmlNode noddr = null;



                    int iitemcount1 = 0;
                    int iitemcount2 = 0;
                    try
                    {
                        noddr = xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("battle_result").SelectSingleNode("private_fairy_reward_list").SelectSingleNode("special_item");
                        //iGuildItem = int.Parse(xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("battle_result").SelectSingleNode("private_fairy_reward_list").SelectSingleNode("special_item").SelectSingleNode("item_count").InnerText);
                    }
                    catch (System.Exception ex)
                    {
                    }
                    if (noddr != null)
                    {
                        try
                        {
                            iitemcount1 = int.Parse(noddr.SelectSingleNode("before_count").InnerText);
                            iitemcount2 = int.Parse(noddr.SelectSingleNode("after_count").InnerText);


                            szlogtemp += "卷：" + iGuildItemCount + "→" + iGuildItem + "收集道具：" + (iitemcount2 - iitemcount1).ToString() + "->" + iitemcount2.ToString() + "\r\n";

                        }
                        catch (System.Exception ex)
                        {
                            szlogtemp += "\r\n";
                        }
                    }
                    else
                    {

                        szlogtemp += "\r\n";
                    }
                    if(iGuildItem != 0)iGuildItemCount = iGuildItem;
                    try
                    {
                        BattleLog bl = new BattleLog(xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("battle_battle"), lv, iitemcount2 - iitemcount1, 0, name);
                        Battles.Add(bl);
                        listBox1.Items.Add(bl);
                        listBox1.DisplayMember = "Text";
                        listBox1.ValueMember = "Value";
                    }
                    catch (System.Exception ex)
                    {

                    }
                    actionlog.Text += "[" + DateTime.Now.ToString() + "]" + szlogtemp; actionlog.WriteInfo(szlogtemp);

                    if(node0 != null)
                    {
                        XmlNode nodec = node0.SelectSingleNode("owner_card_list");
                        if (nodec != null)
                        {
                            try
                            {
                                XmlNodeList nodeCardlist = nodec.SelectNodes("user_card");
                                cardlist = nodeCardlist;
                                actionlog.Text += "总卡数:" + nodeCardlist.Count + "\r\n";
                                int isellnum = 0;
                                string strsell = "";
                                if (nodeCardlist != null && nodeCardlist.Count > 230)
                                {
                                    cardlist = nodeCardlist;
                                    try
                                    {
                                        iSellPrice = int.Parse(textBox4.Text);
                                    }
                                    catch (System.Exception ex)
                                    {

                                    }
                                    string szSellid = "卖：\r\n";
                                    foreach (XmlNode nodes in nodeCardlist)
                                    {
                                        int icardlv = int.Parse(nodes.SelectSingleNode("lv").InnerText);
                                        int icardlvmax = int.Parse(nodes.SelectSingleNode("lv_max").InnerText);
                                        int icardsale_price = int.Parse(nodes.SelectSingleNode("sale_price").InnerText);
                                        int icardhp = int.Parse(nodes.SelectSingleNode("hp").InnerText);
                                        int icardpower = int.Parse(nodes.SelectSingleNode("power").InnerText);
                                        int iHolo = int.Parse(nodes.SelectSingleNode("holography").InnerText);
                                        if (icardlv == 1)
                                        {
                                            if ((icardhp > 1 || icardpower > 1) /*&& iHolo == 0*/ && icardlvmax < 60)
                                            {
                                                if (icardsale_price < iSellPrice)
                                                {
                                                    if (isellnum == 0)
                                                    {
                                                        strsell += nodes.SelectSingleNode("serial_id").InnerText;
                                                    }
                                                    else
                                                    {
                                                        strsell += "," + nodes.SelectSingleNode("serial_id").InnerText;
                                                    }
                                                    szSellid += "ID:" + nodes.ChildNodes[1].InnerText + " lv:" + icardlv + "/" + icardlvmax + "  atk/hp:" + icardpower + "/" + icardhp + "\r\n";
                                                    isellnum++;
                                                }
                                            }
                                        }
                                        else if (icardlvmax < 50 && icardlv < 30)
                                        {
                                            if (isellnum == 0)
                                            {
                                                strsell += nodes.SelectSingleNode("serial_id").InnerText;
                                            }
                                            else
                                            {
                                                strsell += "," + nodes.SelectSingleNode("serial_id").InnerText;
                                            }
                                            szSellid += "ID:" + nodes.ChildNodes[1].InnerText + " lv:" + icardlv + "//" + icardlvmax + "  atk/hp:" + icardpower + "//" + icardhp + "\r\n";
                                            isellnum++;
                                        }
                                        if (isellnum == 30)
                                        {
                                            actionlog.Text += szSellid + "\r\n";
                                            sellcard(strsell);
                                            isellnum = 0;
                                            strsell = "";
                                            szSellid = "卖：\r\n";
                                        }
                                    }
                                    if (strsell != "")
                                    {
                                        actionlog.Text += szSellid;
                                        sellcard(strsell);
                                    }
                                }

                            }
                            catch (System.Exception ex)
                            {

                            }
                        }

                    }
                    
                }
                catch (System.Exception ex)
                {
                    szlogtemp += ex.Message + "\r\n";
                    szActionLog += "[" + DateTime.Now.ToString() + "]" + szlogtemp; actionlog.WriteInfo(szlogtemp);
                }
            }
            return iRe;
        }

        int iArthaCount = 0;
        int[] arthalist = new int[10];
        private int GetAP()
        {
            if (!bDM)
            {
                return -1;
            }
            while (iArthaCount == 0 || iArthaNum == -1 || iArthaNum == iArthaCount)
            {
                SearchArtha();
            }
            ChangeCard(CardChose.ibase3cardnum);
            int ire = 0;
            if(BC >= CardChose.ibase3cardcost )AtactArtha(arthalist[iArthaNum]);
            return ire;
        }
        private int SearchArtha()
        {
            int iRe = -1;
            IDictionary<string, string> parameters = new Dictionary<string, string>()
            {
                {"",""}
            };
            string s0 = "0";
            parameters.Clear();
            parameters.Add("name", Encrypt("无名亚", key12));
            string ulr = "http://" + szhostport + "/connect/app/menu/player_search?cyt=1";
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = szhost;
            cookies.Add(c);
            XmlDocument xml = null;

            while (true)
            {
                try
                {
                    xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                    break;
                }
                catch (System.Exception ex)
                {
                    continue;
                }
            }

            if (xml.InnerText != "")
            {
                try
                {
                    szCookie = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("session_id").InnerText;
                    if (int.Parse(xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("code").InnerText) != 0)
                    {
                        return iRe;
                    }
                    XmlNode node0 = xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("player_search").SelectSingleNode("user_list");
                    iArthaCount = 0;
                    for (int i = 0; i < 9; i++)
                    {
                        if (int.Parse(node0.ChildNodes[i + 1].SelectSingleNode("town_level").InnerText) < 5)
                        {
                            arthalist[iArthaCount] = int.Parse(node0.ChildNodes[i + 1].SelectSingleNode("id").InnerText);
                            iArthaCount++;
                        }
                    }
                    iArthaNum = 0;

                    iRe = 0;
                }
                catch (System.Exception ex)
                {
                }
            }
            return iRe;
        }

        DateTime dtold = DateTime.Now;
        bool bDM = false;
        int iArthaNum = 0;
        private int AtactArtha(int iArtha)
        {
            int iRe = -1;
            DateTime dt = DateTime.Now;
            TimeSpan ts = dt - dtold;
            if (ts.TotalSeconds < 16 || !bDM)
            {
                return iRe;
            }
            iArthaNum++;
            IDictionary<string, string> parameters = new Dictionary<string, string>()
            {
                {"",""}
            };
            string s0 = "0";
            parameters.Clear();
            parameters.Add("lake_id", Encrypt(s0, key12));
            parameters.Add("parts_id", Encrypt(s0, key12));
            parameters.Add("user_id", Encrypt(iArtha.ToString(), key12));
            string ulr = "http://" + szhostport + "/connect/app/battle/battle?cyt=1";
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = szhost;
            cookies.Add(c);
            XmlDocument xml = null;

            while (true)
            {
                try
                {
                    xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                    break;
                }
                catch (System.Exception ex)
                {
                    continue;
                }
            }

            if (xml.InnerText != "")
            {
                string szlogtemp = "点名：";
                try
                {
                    szCookie = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("session_id").InnerText;
                    if (int.Parse(xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("code").InnerText) != 0)
                    {
                        System.Diagnostics.Trace.WriteLine("error code :" + xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("code").InnerText
                            + " message: " + xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("message").InnerText + "\r\n");
                        szlogtemp += xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("message").InnerText + "\r\n";
                        szActionLog += "[" + DateTime.Now.ToString() + "]" + szlogtemp; actionlog.WriteInfo(szlogtemp);
                        return int.Parse(xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("code").InnerText);
                    }
                    XmlNode node0 = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("your_data"); szCharName = node0.SelectSingleNode("name").InnerText;
                    XmlNode nodeBC = node0.SelectSingleNode("bc");
                    int oldAp = AP;
                    int oldBC = BC;
                    BC = int.Parse(nodeBC.SelectSingleNode("current").InnerText);
                    MaxBc = int.Parse(nodeBC.SelectSingleNode("max").InnerText);
                    XmlNode nodeAP = node0.SelectSingleNode("ap");
                    AP = int.Parse(nodeAP.SelectSingleNode("current").InnerText);
                    MaxAP = int.Parse(nodeAP.SelectSingleNode("max").InnerText);

                    szlogtemp += "AP:" + oldAp.ToString() + "-" + AP.ToString() + " BC:" + oldBC.ToString() + "-" + BC.ToString() + "\r\n";
                    actionlog.Text += "[" + DateTime.Now.ToString() + "]" + szlogtemp; actionlog.WriteInfo(szlogtemp);
                    iRe = 0;

                    dtold = dt;
                }
                catch (System.Exception ex)
                {
                    szlogtemp += ex.Message + "\r\n";
                    actionlog.Text += "[" + DateTime.Now.ToString() + "]" + szlogtemp; actionlog.WriteInfo(szlogtemp);
                }
            }
            return iRe;
        }



        private int fairybattle(int iU, int iS)
        {
            int iRe = -1;
            //             while (ts.TotalSeconds < 12)
            //             {
            //                 ts = DateTime.Now - dtold1;
            //                 Thread.Sleep(1000);
            //             }
            IDictionary<string, string> parameters = new Dictionary<string, string>()
            {
                {"",""}
            };
            parameters.Clear();
            parameters.Add("serial_id", Encrypt(iS.ToString(), key12));
            parameters.Add("user_id", Encrypt(iU.ToString(), key12));
            string ulr = "http://" + szhostport + "/connect/app/exploration/fairybattle?cyt=1";
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = szhost;
            cookies.Add(c);
            XmlDocument xml = null;

            while (true)
            {
                try
                {
                    xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                    break;
                }
                catch (System.Exception ex)
                {
                    return iRe;
                }
            }
            bWinner = false;
            if (xml != null&&xml.InnerText!="")
            {
                string szlogtemp = "战斗：";
                try
                {
                    szCookie = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("session_id").InnerText;
                    if (int.Parse(xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("code").InnerText) != 0)
                    {
                        szlogtemp += xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("message").InnerText + "\r\n";
                        szActionLog += "[" + DateTime.Now.ToString() + "]" + szlogtemp; actionlog.WriteInfo(szlogtemp);
                        iRe = 1001;
                        return iRe;
                    }
                    XmlNode node0 = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("your_data");//szCharName = node0.SelectSingleNode("name").InnerText + "正在挂机";

                    XmlNode nodeBC = node0.SelectSingleNode("bc");
                    int oldBC = BC;
                    BC = int.Parse(nodeBC.SelectSingleNode("current").InnerText);
                    MaxBc = int.Parse(nodeBC.SelectSingleNode("max").InnerText);
                    XmlNode nodeAP = node0.SelectSingleNode("ap");
                    AP = int.Parse(nodeAP.SelectSingleNode("current").InnerText);
                    MaxAP = int.Parse(nodeAP.SelectSingleNode("max").InnerText);
                    szlogtemp += " BC:" + oldBC.ToString() + "->" + BC.ToString() + " ";
                    int exp1 = int.Parse(xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("battle_result").SelectSingleNode("before_exp").InnerText);
                    int exp2 = int.Parse(xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("battle_result").SelectSingleNode("after_exp").InnerText);
                    bWinner = int.Parse(xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("battle_result").SelectSingleNode("winner").InnerText) == 1;
                    iRe = 0;

                    if (node0 != null)
                    {
                        XmlNode nodec = node0.SelectSingleNode("owner_card_list");
                        if (nodec != null)
                        {
                            try
                            {
                                XmlNodeList nodeCardlist = nodec.SelectNodes("user_card");
                                cardlist = nodeCardlist;
                                actionlog.Text += "总卡数:" + nodeCardlist.Count + "\r\n";
                                int isellnum = 0;
                                string strsell = "";
                                if (nodeCardlist != null && nodeCardlist.Count > 180)
                                {
                                    cardlist = nodeCardlist;
                                    try
                                    {
                                        iSellPrice = int.Parse(textBox4.Text);
                                    }
                                    catch (System.Exception ex)
                                    {

                                    }
                                    string szSellid = "卖：\r\n";
                                    foreach (XmlNode nodes in nodeCardlist)
                                    {
                                        int icardlv = int.Parse(nodes.SelectSingleNode("lv").InnerText);
                                        int icardlvmax = int.Parse(nodes.SelectSingleNode("lv_max").InnerText);
                                        int icardsale_price = int.Parse(nodes.SelectSingleNode("sale_price").InnerText);
                                        int icardhp = int.Parse(nodes.SelectSingleNode("hp").InnerText);
                                        int icardpower = int.Parse(nodes.SelectSingleNode("power").InnerText);
                                        int iHolo = int.Parse(nodes.SelectSingleNode("holography").InnerText);
                                        if (icardlv == 1)
                                        {
                                            if ((icardhp > 1 || icardpower > 1) && iHolo == 0 && icardlvmax < 50)
                                            {
                                                if (icardsale_price < iSellPrice)
                                                {
                                                    if (isellnum == 0)
                                                    {
                                                        strsell += nodes.SelectSingleNode("serial_id").InnerText;
                                                    }
                                                    else
                                                    {
                                                        strsell += "," + nodes.SelectSingleNode("serial_id").InnerText;
                                                    }
                                                    szSellid += "ID:" + nodes.ChildNodes[1].InnerText + " lv:" + icardlv + "/" + icardlvmax + "  atk/hp:" + icardpower + "/" + icardhp + "\r\n";
                                                    isellnum++;
                                                }
                                            }
                                        }
                                        else if (icardlvmax < 50 && icardlv < 30)
                                        {
                                            if (isellnum == 0)
                                            {
                                                strsell += nodes.SelectSingleNode("serial_id").InnerText;
                                            }
                                            else
                                            {
                                                strsell += "," + nodes.SelectSingleNode("serial_id").InnerText;
                                            }
                                            szSellid += "ID:" + nodes.ChildNodes[1].InnerText + " lv:" + icardlv + "//" + icardlvmax + "  atk/hp:" + icardpower + "//" + icardhp + "\r\n";
                                            isellnum++;
                                        }
                                        if (isellnum == 30)
                                        {
                                            actionlog.Text += szSellid + "\r\n";
                                            sellcard(strsell);
                                            isellnum = 0;
                                            strsell = "";
                                            szSellid = "卖：\r\n";
                                        }
                                    }
                                    if (strsell != "")
                                    {
                                        actionlog.Text += szSellid;
                                        sellcard(strsell);
                                    }
                                }

                            }
                            catch (System.Exception ex)
                            {

                            }
                        }

                    }
                    
                    if (bWinner)
                    {
                        szlogtemp += "-战斗胜利-";
                    }
                    szlogtemp += "经验" + exp1.ToString() + "->" + exp2.ToString();

                    XmlNode noddr = null;
                    try
                    {
                        noddr = xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("battle_result").SelectSingleNode("special_item");
                    }
                    catch (System.Exception ex)
                    {
                        szlogtemp += "\r\n";
                    }

                    int iitemcount1 = 0;
                    int iitemcount2 = 0;
                    if (noddr != null)
                    {
                        try
                        {
                            iitemcount1 = int.Parse(noddr.SelectSingleNode("before_count").InnerText);
                            iitemcount2 = int.Parse(noddr.SelectSingleNode("after_count").InnerText);


                            szlogtemp += "收集道具：" + (iitemcount2 - iitemcount1).ToString() + "->" + iitemcount2.ToString() + "\r\n";
                        }
                        catch (System.Exception ex)
                        {
                            szlogtemp += "\r\n";
                        }
                    }

                    BattleLog bl = new BattleLog(xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("battle_battle"), lv, iitemcount2 - iitemcount1, 0,name);
                    Battles.Add(bl);
                    listBox1.Items.Add(bl);
                    listBox1.DisplayMember = "Text";
                    listBox1.ValueMember = "Value";
                    actionlog.Text += "[" + DateTime.Now.ToString() + "]" + szlogtemp; actionlog.WriteInfo(szlogtemp);
                }
                catch (System.Exception ex)
                {
                    szlogtemp += ex.Message + "\r\n";
                    szActionLog += "[" + DateTime.Now.ToString() + "]" + szlogtemp; actionlog.WriteInfo(szlogtemp);
                }
            }
            return iRe;
        }

        int nowFairyID = 0;
        List<int> fairylist = new List<int>();
        private void guildEvent()
        {
            if (checkBox3.Checked)
            {
//                 int ire = getGuidIFO();
//                 if (ire == 2)
//                 {
//                     return;
//                 }
                while (iGuildItemCount > 10)
                {
                    int ire = getGuidIFO();
                    while (ire == 4 || ire == 1) ire = getGuidIFO();
                    if (ire == 2)
                    {
                        return;
                    }
                    ChangeCard(CardChose.isubcardnum, 0);

                    TimeSpan ts = DateTime.Now - guildfairytime;
                    while (ts.TotalSeconds < 15)
                    {
                        Thread.Sleep(1000);
                        ts = DateTime.Now - guildfairytime;
                    }
                    
                    GuildBattle(iGuildID, serial_id);
                }
            }
        }
        private int getGuildFairyIfo()
        {
            
            int iReturn = -1;
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = szhost;
            cookies.Add(c);
            string ulr = "http://" + szhostport + "/connect/app/private_fairy/private_fairy_select?cyt=1";
            XmlDocument xml = null;
            while (true)
            {
                try
                {
                    xml = CreatePostHttpResponse(ulr, null, (int?)50000, string.Empty, Encoding.Default, cookies);
                    break;
                }
                catch (System.Exception ex)
                {
                    continue; ;
                }
            }
            try
            {
                if (Properties.Settings.Default.xmlsave)xml.Save("fairy.xml");
                XmlNode node0 = xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("fairy_select");
                XmlNodeList nodefairies = node0.SelectNodes("fairy_event");
                XmlNodeList nodeusers = node0.SelectNodes("user");
                bool bg = true;
                int[] cardc1 = { 0, 0 };
                int[] cardc2 = { 0, 0 };
                cardc1 = CardChose.getDeckNum(9999);
                cardc2 = CardChose.getDeckNum(100000);
                bool bHPMODE = cardc2 != cardc1;
                foreach (XmlNode nodes in nodefairies)
                {
                    //string szUser = nodes.SelectSingleNode("user").SelectSingleNode("name").InnerText;
                    int iuserid = int.Parse(nodes.SelectSingleNode("fairy").SelectSingleNode("discoverer_id").InnerText);
                    string szboss = nodes.SelectSingleNode("fairy").SelectSingleNode("name").InnerText;
                    int iserialid = int.Parse(nodes.SelectSingleNode("fairy").SelectSingleNode("serial_id").InnerText);
                    int lv = int.Parse(nodes.SelectSingleNode("fairy").SelectSingleNode("lv").InnerText);
                    hp = int.Parse(nodes.SelectSingleNode("fairy").SelectSingleNode("hp").InnerText);
                    hp_max = int.Parse(nodes.SelectSingleNode("fairy").SelectSingleNode("hp").InnerText);
                    bool balive = int.Parse(nodes.SelectSingleNode("put_down").InnerText) == 1 || int.Parse(nodes.SelectSingleNode("put_down").InnerText) == 4;
                    bool bDefead = int.Parse(nodes.SelectSingleNode("put_down").InnerText) == 5;
                    bool brare = int.Parse(nodes.SelectSingleNode("fairy").SelectSingleNode("rare_flg").InnerText) == 1;
                    if (iuserid == iNowUserid)
                    {
                        if (balive)
                        {
                            //fairyhistory(iuserid, iserialid);
                            bg = false;
                        }
                    }
                    if (bDefead)
                    {
                        fairyhistory(iuserid, iserialid);
                    }
                    if (balive)
                    {
                        int hptemp = hp < 10000 ? 10000 : hp;
                        cardc1 = CardChose.getDeckNum(hptemp);
                        if (cardc1[1] != 0 && BC >= cardc1[1] && bHPMODE)
                        {
                            foreach (XmlNode nodeuser in nodeusers)
                            {
                                if (nodeuser.SelectSingleNode("id").InnerText == iuserid.ToString())
                                {
                                    name = nodeuser.SelectSingleNode("name").InnerText;
                                }
                            }
                            actionlog.Text += "尾刀攻击：" + name + "-lv" + lv.ToString() + szboss + "\r\n";
                            ChangeCard(cardc1[0], 0);
                            fairytop(iuserid, iserialid);
                            if (1001 == guildfairybattle(iuserid, iserialid))
                            {
                                bg = false;
                                break;
                            }
                        }
                        else 
                        {
                            foreach (XmlNode nodeuser in nodeusers)
                            {
                                if (nodeuser.SelectSingleNode("id").InnerText == iuserid.ToString())
                                {
                                    name = nodeuser.SelectSingleNode("name").InnerText;
                                    
                                }
                            }
                            actionlog.Text += "攻击：" + name + "-lv" + lv.ToString() + szboss + "\r\n";
                            this.lv = lv;

                            if (!brare) cardc = CardChose.getDeckNum(lv);
                            else cardc = CardChose.getDeckNum(lv + 1000);
                            if (iuserid == iNowUserid && !wolfFairylist.Contains(iserialid) && (!brare || !checkBox5.Checked))
                            {

                                ChangeCard(CardChose.iwolfmusumecardnum, 0);

                                fairytop(iuserid, iserialid);
                                if (1001 == guildfairybattle(iuserid, iserialid))
                                {
                                    bg = false;
                                    break;
                                }
                                else
                                {
                                    wolfFairylist.Add(iserialid);
                                    if (wolfFairylist.Count > 30)
                                    {
                                        wolfFairylist.RemoveAt(0);
                                    }
                                    Thread.Sleep(10000);
                                } 
                            }
                            else if(BC > cardc[1])
                            {
                                ChangeCard(cardc[0], 0);
                                fairytop(iuserid, iserialid);
                                if (1001 == guildfairybattle(iuserid, iserialid))
                                {
                                    bg = false;
                                    break;
                                }
                                else
                                {
                                    fairylist.Add(iserialid);
                                    if (fairylist.Count > 100)
                                    {
                                        fairylist.RemoveAt(0);
                                    }
                                    Thread.Sleep(10000);
                                }

                                //guildEvent();
                            }
                            else if (!wolfFairylist.Contains(iserialid) && !fairylist.Contains(iserialid))
                            {
                                ChangeCard(CardChose.iwolfmusumecardnum, 0);
                                fairytop(iuserid, iserialid);
                                if (1001 == guildfairybattle(iuserid, iserialid))
                                {
                                    bg = false;
                                    break;
                                }
                                else
                                {
                                    wolfFairylist.Add(iserialid);
                                    if (wolfFairylist.Count > 100)
                                    {
                                        wolfFairylist.RemoveAt(0);
                                    }
                                    Thread.Sleep(10000);
                                }
                            }
                        }
                    }
                }
                bExplore = bg;
            }
            catch (System.Exception ex)
            {
                serial_id = 0;
            }
            if (DateTime.Now.Hour < 1 || DateTime.Now.Hour > 3)
            {
                guildEvent();
            }
            return iReturn;
        }
        List<int> wolfFairylist = new List<int>();
        private void getFairyFloor(int iuser,int ifairy)
        {
            IDictionary<string, string> parameters = new Dictionary<string, string>()
            {
                {"",""}
            };
            parameters.Clear();
            parameters.Add("check", Encrypt("1", key12));
            parameters.Add("serial_id", Encrypt(ifairy.ToString(), key12));
            parameters.Add("user_id", Encrypt(iuser.ToString(), key12));
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = szhost;
            cookies.Add(c);
            string ulr = "http://" + szhostport + "/connect/app/exploration/fairy_floor?cyt=1";
            XmlDocument xml = null;
            while (true)
            {
                try
                {
                    xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                    break;
                }
                catch (System.Exception ex)
                {
                    continue; ;
                }
            }
            //if (Properties.Settings.Default.xmlsave)xml.Save("fairyinfo.xml");
            try
            {
                XmlNode node0 = xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("fairy_floor").SelectSingleNode("explore").SelectSingleNode("fairy");
                hp = int.Parse(node0.SelectSingleNode("hp").InnerText);
                lv = int.Parse(node0.SelectSingleNode("lv").InnerText);
                hp_max = int.Parse(node0.SelectSingleNode("hp_max").InnerText);
            }
            catch (System.Exception ex)
            {
            	
            }


        }
        private int getFairyIfo()
        {
            int iReturn = -1;
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = szhost;
            cookies.Add(c);
            string ulr = "http://" + szhostport + "/connect/app/menu/fairyselect?cyt=1";
            XmlDocument xml = null;
            while (true)
            {
                try
                {
                    xml = CreatePostHttpResponse(ulr, null, (int?)50000, string.Empty, Encoding.Default, cookies);
                    break;
                }
                catch (System.Exception ex)
                {
                    continue; ;
                }
            }
            try
            {
                if (Properties.Settings.Default.xmlsave)xml.Save("fairy.xml");
                XmlNode node0 = xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("fairy_select");
                XmlNodeList nodefairies = node0.SelectNodes("fairy_event");
                bool bg = true;
                int[] cardc1 = CardChose.getDeckNum(9999);
                int[] cardc2 = CardChose.getDeckNum(100000);
                bool bHPMODE = cardc2 != cardc1;
                foreach (XmlNode nodes in nodefairies)
                {
                    string szUser = nodes.SelectSingleNode("user").SelectSingleNode("name").InnerText;
                    name = szUser;
                    int iuserid = int.Parse(nodes.SelectSingleNode("user").SelectSingleNode("id").InnerText);
                    string szboss = nodes.SelectSingleNode("fairy").SelectSingleNode("name").InnerText;
                    int iserialid = int.Parse(nodes.SelectSingleNode("fairy").SelectSingleNode("serial_id").InnerText);
                    int lv = int.Parse(nodes.SelectSingleNode("fairy").SelectSingleNode("lv").InnerText);
                    //int hp = int.Parse(nodes.SelectSingleNode("fairy").SelectSingleNode("hp").InnerText);
                    bool balive = int.Parse(nodes.SelectSingleNode("put_down").InnerText) == 1;
                    bool brare = szboss.Contains("觉醒");
                    if (iuserid == iNowUserid)
                    {
                        if (balive)
                        {
                            bg = false;
                        }
                    }

                    if (balive)
                    {

                        getFairyFloor(iuserid, iserialid);
                        int hptemp = hp < 10000 ? 10000 : hp;
                        cardc1 = CardChose.getDeckNum(hptemp);
                        if (!bExplore )
                        {
                            if (bHPMODE && cardc1[1] != 0 && BC > cardc1[1] && iuserid == iNowUserid)
                            {


                                ChangeCard(cardc1[0]);
                                actionlog.Text += "尾刀攻击：" + szUser + "-lv" + lv.ToString() + szboss + "\r\n";
                                this.lv = lv;
                                if (1001 == fairybattle(iuserid, iserialid))
                                {
                                    bg = false;
                                    break;
                                }

                            }
                            else if (!fairylist.Contains(iserialid))
                            {
                                cardc = brare ? CardChose.getDeckNum(lv + 1000) : CardChose.getDeckNum(lv); 
                                if (BC > cardc[1])
                                {
                                    ChangeCard(cardc[0]);
                                    actionlog.Text += "攻击：" + szUser + "-lv" + lv.ToString() + szboss + "\r\n";
                                    this.lv = lv;
                                    if (1001 == fairybattle(iuserid, iserialid))
                                    {
                                        bg = false;
                                        break;
                                    }
                                    else
                                    {
                                        fairylist.Add(iserialid);
                                        if (fairylist.Count > 30)
                                        {
                                            fairylist.RemoveAt(0);
                                        }
                                        Thread.Sleep(10000);
                                    }
                                }
                            }
                        }
                        else 
                        {
                            if (bHPMODE && cardc1[1] != 0 && BC > cardc1[1])
                            {
                                ChangeCard(cardc1[0]);
                                actionlog.Text += "尾刀攻击：" + szUser + "-lv" + lv.ToString() + szboss + "\r\n";
                                this.lv = lv;
                                if (1001 == fairybattle(iuserid, iserialid))
                                {
                                    break;
                                }
                                else
                                {
                                    fairylist.Add(iserialid);
                                    if (fairylist.Count > 30)
                                    {
                                        fairylist.RemoveAt(0);
                                    }
                                    Thread.Sleep(10000);
                                }
                            }
                            else if (!fairylist.Contains(iserialid))
                            {
                                cardc = brare ? CardChose.getDeckNum(lv + 1000) : CardChose.getDeckNum(lv);
                                if (BC > cardc[1])
                                {
                                    ChangeCard(cardc[0]);
                                    actionlog.Text += "攻击：" + szUser + "-lv" + lv.ToString() + szboss + "\r\n";
                                    this.lv = lv;
                                    if (1001 == fairybattle(iuserid, iserialid))
                                    {
                                        break;
                                    }
                                    else
                                    {
                                        fairylist.Add(iserialid);
                                        if (fairylist.Count > 30)
                                        {
                                            fairylist.RemoveAt(0);
                                        }
                                        Thread.Sleep(10000);
                                    }
                                }
                            }
                        }
                        //else if (!fairylist.Contains(iserialid))
                        //{
                        //    ChangeCard(CardChose.iwolfmusumecardnum);
                        //    actionlog.Text += "攻击：" + szUser + "-lv" + lv.ToString() + szboss + "\r\n";
                        //    this.lv = lv;
                        //    if (1001 == fairybattle(iuserid, iserialid))
                        //    {
                        //        break;
                        //    }
                        //    else
                        //    {
                        //        fairylist.Add(iserialid);
                        //        if (fairylist.Count > 30)
                        //        {
                        //            fairylist.RemoveAt(0);
                        //        }
                        //        Thread.Sleep(10000);
                        //    }
                        //}
                    }
                }
                bExplore = bg;
            }
            catch (System.Exception ex)
            {
                serial_id = 0;
            }
            return iReturn;
        }
        private int getGuidIFO()
        {
            int iReturn = -1;
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = szhost;
            cookies.Add(c);
            string ulr = "http://" + szhostport + "/connect/app/guild/guild_top?cyt=1";

            XmlDocument xml = null;
            while (true)
            {
                try
                {
                    xml = CreatePostHttpResponse(ulr, null, (int?)50000, string.Empty, Encoding.Default, cookies);
                    break;
                }
                catch (System.Exception ex)
                {
                    continue; ;
                }
            }
            try
            {
                if (Properties.Settings.Default.xmlsave)xml.Save("guild.xml");
                XmlNode node0 = xml.SelectSingleNode("response").SelectSingleNode("body");
                string szName = node0.ChildNodes[0].Name;

                XmlNode nodeyd = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("your_data");//szCharName = node0.SelectSingleNode("name").InnerText + "正在挂机";
                if (nodeyd != null)
                {
                    XmlNodeList itemlist = nodeyd.SelectNodes("itemlist");
                    if (itemlist != null)
                    {
                        foreach (XmlNode nodeitem in itemlist)
                        {
                            int id = int.Parse(nodeitem.SelectSingleNode("item_id").InnerText);
                            if (id == 202)
                            {
                                iGuildItemCount = int.Parse(nodeitem.SelectSingleNode("num").InnerText);
                            }
                        }
                    }
                }
                    
                
                if (szName == "guild_top" || szName == "guild_defeat_event")
                {
                    XmlNode node1 = node0.SelectSingleNode(szName).SelectSingleNode("guild_top_update");
                    XmlNode nodd3 = node1.SelectSingleNode("guild_reward_list");
                    if (nodd3 != null && szName == "guild_top")
                    {
                        bBonus = true;
                        string szBX = "";
                        int ibx = int.Parse(nodd3.SelectSingleNode("reward_box_list").SelectSingleNode("box_type").InnerText);
                        switch (ibx)
                        {
                            case 10101:
                                szBX = "白金箱";
                                break;
                            case 10102:
                                szBX = "金箱";
                                break;
                            case 10103:
                                szBX = "银箱";
                                break;
                            case 10104:
                                szBX = "铜箱";
                                break;
                            case 10105:
                                szBX = "木箱";
                                break;
                        }
                        int ibxn = int.Parse(nodd3.SelectSingleNode("reward_box_list").SelectSingleNode("box_num").InnerText);
                        actionlog.Text += "[" + DateTime.Now.ToString() + "]" + "发现强敌：获得" + szBX + "*" + ibxn.ToString() + "\r\n";
                        actionlog.WriteInfo("发现强敌：获得" + szBX + "*" + ibxn.ToString() + "\r\n");
                    }
                    else if (szName == "guild_defeat_event")
                    {
                        nodd3 = node0.SelectSingleNode(szName).SelectSingleNode("guild_reward_list");
                        string szBX = "";
                        int ibx = int.Parse(nodd3.SelectSingleNode("reward_box_list").SelectSingleNode("box_type").InnerText);
                        switch (ibx)
                        {
                            case 10101:
                                szBX = "白金箱";
                                break;
                            case 10102:
                                szBX = "金箱";
                                break;
                            case 10103:
                                szBX = "银箱";
                                break;
                            case 10104:
                                szBX = "铜箱";
                                break;
                            case 10105:
                                szBX = "木箱";
                                break;
                        }
                        int ibxn = int.Parse(nodd3.SelectSingleNode("reward_box_list").SelectSingleNode("box_num").InnerText);
                        actionlog.Text += "[" + DateTime.Now.ToString() + "]" + nodd3 != null ? "强敌已死，获得" + szBX + "*" + ibxn.ToString() + "\r\n" : "强敌已死\r\n";
                        actionlog.WriteInfo(nodd3 != null ? "强敌已死，获得" + szBX + "*" + ibxn.ToString() + "\r\n" : "强敌已死\r\n");
                    }
                    else
                    {
                        bBonus = false;
                    }
                    XmlNode node2 = node1.SelectSingleNode("fairy");
                    XmlNode nodeweak = node1.SelectSingleNode("guild_fairy_weak");
                    if (nodeweak != null && bAutojob)
                    {
                        int iweakid = int.Parse(nodeweak.SelectSingleNode("id").InnerText);
                        if (iweakid != iJobID)
                        {
                            if (-2 != changejob(iweakid)) iJobID = iweakid;
                        }
                    }
                    XmlNodeList nodelogs = node1.SelectNodes("guild_log");
                    //                     szBattleLog = string.Empty;
                    //                     foreach (XmlNode nodes in nodelogs)
                    //                     {
                    //                         szBattleLog += nodes.SelectSingleNode("log_time").InnerText + " - ";
                    //                         szBattleLog += nodes.SelectSingleNode("user_name").InnerText + ":   ";
                    //                         szBattleLog += nodes.SelectSingleNode("message").InnerText + "\r\n\r\n";
                    //                     }
                    serial_id = int.Parse(node2.SelectSingleNode("serial_id").InnerText);
                    lv = int.Parse(node2.SelectSingleNode("lv").InnerText);
                    hp = int.Parse(node2.SelectSingleNode("hp").InnerText);
                    hp_max = int.Parse(node2.SelectSingleNode("hp_max").InnerText);
                    bname = node2.SelectSingleNode("name").InnerText;
                    XmlNode nodef = node1.SelectSingleNode("force_gauge");
                    if (nodef != null)
                    {
                        int iOwn = int.Parse(nodef.SelectSingleNode("own").InnerText);
                        int iRival = int.Parse(nodef.SelectSingleNode("rival").InnerText);
                        int iTotal = int.Parse(nodef.SelectSingleNode("total").InnerText);
                        dWin = (double)(iOwn - iRival) / iTotal / 2;
                    }
                    iGuildID = int.Parse(node2.SelectSingleNode("discoverer_id").InnerText);
                    int timel = int.Parse(node2.SelectSingleNode("time_limit").InnerText);
                    actionlog.Text += "刷新boss：" + bname + "__Lv:" + lv + "__HP" + hp + "/" + hp_max + "\r\n";
                    iReturn = 0;
                    if (int.Parse(node2.SelectSingleNode("master_boss_id").InnerText) == iSubBossID)
                    {
                        bSub = true;
                        if (timel > 7080 && !(DateTime.Now.Hour > 23 || DateTime.Now.Hour < 1))
                        {
                            iReturn = 3;
                        }
                    }
                    else if (iSubBossID == 0 && hp_max < 1000000)
                    {
                        iSubBossID = int.Parse(node2.SelectSingleNode("master_boss_id").InnerText);
                        bSub = true;
                        if (timel > 7080 && !(DateTime.Now.Hour > 23 || DateTime.Now.Hour < 1))
                        {
                            iReturn = 3;
                        }
                    }
                    else
                    {
                        bSub = false;
                        iReturn = 3;
                    }

                    if (szName == "guild_defeat_event")
                    {
                        serial_id = 0;
                        iReturn = 4;
                    }
                }
                else if (szName == "guild_fairy_event")
                {
                    iReturn = 1;
                    actionlog.Text += "强敌出现\r\n";
                }
                else if (szName == "guild_top_no_fairy")
                {
                    iReturn = 2;

                    master_boss_id = int.Parse(node0.SelectSingleNode("guild_top_no_fairy").SelectSingleNode("guild_boss").SelectSingleNode("master_boss_id").InnerText);
                    iSubBossID = int.Parse(node0.SelectSingleNode("guild_top_no_fairy").SelectSingleNode("guild_boss").SelectSingleNode("sub_boss_id").InnerText);
                    hp = 0;
                    serial_id = 0;
                }
            }
            catch (System.Exception ex)
            {
                serial_id = 0;
            }
            return iReturn;
        }
        private int getRankINFO()
        {
            int iRe = -1;
            IDictionary<string, string> parameters = new Dictionary<string, string>()
            {
                {"",""}
            };
            parameters.Clear();
            string ulr = "http://" + szhostport + "/connect/app/guild/guild_info?cyt=1";
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = szhost;
            cookies.Add(c);
            XmlDocument xml = null;

            try
            {
                xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
            }
            catch (System.Exception ex)
            {
                return -1;
            }
            if (xml == null)
            {
                return -1;
            }

            if (xml != null&&xml.InnerText!="")
            {
                try
                {
                    if (int.Parse(xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("code").InnerText) != 0)
                    {
                        return iRe;
                    }
                    szCookie = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("session_id").InnerText;
                    XmlNode node0 = xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("guild_info");
                    labelgrk = node0.SelectSingleNode("user_rank").InnerText;
                    labelgzg = node0.SelectSingleNode("user_hunting_point").InnerText;
                    labelzzg = node0.SelectSingleNode("guild_hunting_point").SelectSingleNode("own_guild_point").InnerText;
                    labelzrg = node0.SelectSingleNode("guild_hunting_point").SelectSingleNode("own_guild_dairy_point").InnerText;
                    labelzrk = node0.SelectSingleNode("own_guild_rank").InnerText;
                    labelxzg = node0.SelectSingleNode("guild_hunting_point").SelectSingleNode("rival_guild_point").InnerText;
                    labelxrg = node0.SelectSingleNode("guild_hunting_point").SelectSingleNode("rival_guild_dairy_point").InnerText;
                    labelxrk = node0.SelectSingleNode("rival_guild_rank").InnerText;

                }
                catch (System.Exception ex)
                {
                }
            }
            return iRe;
        }

        private int changejob(int i)
        {
            IDictionary<string, string> parameters = new Dictionary<string, string>()
            {
                {"",""}
            };
            parameters.Clear();
            parameters.Add("jid", Encrypt(i.ToString(), key12));
            string ulr = "http://" + szhostport + "/connect/app/job/change_job?cyt=1";
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = szhost;
            cookies.Add(c);
            XmlDocument xml = null;
            string szname;
            switch (i)
            {
                case 1:
                    szname = "士兵|" + lv;
                    break;
                case 2:
                    szname = "武斗|" + lv;
                    break;
                case 3:
                    szname = "操纵|" + lv;
                    break;
                case 4:
                    szname = "弓手|" + lv;
                    break;
                case 5:
                    szname = "风水|" + lv;
                    break;
                case 6:
                    szname = "曜魔|" + lv;
                    break;
                case 7:
                    szname = "会长|" + lv;
                    break;
                case 8:
                    szname = "妹|" + lv;
                    break;
                case 9:
                    szname = "雀鬼|" + lv;
                    break;
                default:
                    szname = "??|" + lv;
                    break;
            }
            while (true)
            {
                try
                {
                    xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                    break;
                }
                catch (System.Exception ex)
                {
                    return -2;
                }
            }
            if (xml != null && xml.InnerText != "")
            {
                //if (int.Parse(xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("code").InnerText) == 0)
                //{
                //    return -1;
                //}
                szCookie = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("session_id").InnerText;
                actionlog.Text += "更换职业：" + szname + "\r\n";
            }
            return 0;
        }
        private int sellcard(string str)
        {
            IDictionary<string, string> parameters = new Dictionary<string, string>()
            {
                {"",""}
            };
            parameters.Clear();
            parameters.Add("serial_id", Encrypt(str, key12));
            string ulr = "http://" + szhostport + "/connect/app/trunk/sell?cyt=1";
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = szhost;
            cookies.Add(c);
            XmlDocument xml = null;

            while (true)
            {
                try
                {
                    xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                    break;
                }
                catch (System.Exception ex)
                {
                    continue;
                }
            }
            if (xml != null&&xml.InnerText!="")
            {
                if (int.Parse(xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("code").InnerText) == 8000)
                {
                    return 0;
                }
                szCookie = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("session_id").InnerText;
                XmlNode node0 = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("your_data"); szCharName = node0.SelectSingleNode("name").InnerText;
                XmlNode nodeBC = node0.SelectSingleNode("bc");
                BC = int.Parse(nodeBC.SelectSingleNode("current").InnerText);
                MaxBc = int.Parse(nodeBC.SelectSingleNode("max").InnerText);
                XmlNode nodeAP = node0.SelectSingleNode("ap");
                AP = int.Parse(nodeAP.SelectSingleNode("current").InnerText);
                MaxAP = int.Parse(nodeAP.SelectSingleNode("max").InnerText);
                XmlNodeList nodeCardlist = node0.SelectSingleNode("owner_card_list").SelectNodes("user_card");


                if (nodeCardlist != null && nodeCardlist.Count != 0)
                {
                    cardlist = nodeCardlist;
                    actionlog.Text += "卖卡成功-卡数:" + nodeCardlist.Count + "\r\n\r\n";
                }
                if (nodeCardlist.Count >= 230)
                {
                    return -1;
                }
            }
            return 0;
        }
        int errorcount = 0;
        private void getGuildFairyRewards()
        {
            //iNowUserid = getuserid();
            IDictionary<string, string> parameters = new Dictionary<string, string>()
            {
                {"",""}
            };
            parameters.Clear();
            string ulr = "http://" + szhostport + "/connect/app/private_fairy/private_fairy_rewards?cyt=1";
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = szhost;
            cookies.Add(c);
            XmlDocument xml = null;

            //while (true)
            //{
            //    try
            //    {
                    xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
            //        break;
            //    }
            //    catch (System.Exception ex)
            //    {
            //        continue;
            //    }
            //}
            if (xml != null && xml.InnerText != "")
            {
                //                 if (int.Parse(xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("code").InnerText) != 0)
                //                 {
                //                     return 0;
                //                 }
                errorcount = 0;
                szCookie = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("session_id").InnerText;
                XmlNode node0 = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("your_data");
                if (node0 != null)
                {

                    szCharName = node0.SelectSingleNode("name").InnerText;
                    XmlNode nodeBC = node0.SelectSingleNode("bc");
                    BC = int.Parse(nodeBC.SelectSingleNode("current").InnerText);
                    MaxBc = int.Parse(nodeBC.SelectSingleNode("max").InnerText);
                    XmlNode nodeAP = node0.SelectSingleNode("ap");
                    AP = int.Parse(nodeAP.SelectSingleNode("current").InnerText);
                    MaxAP = int.Parse(nodeAP.SelectSingleNode("max").InnerText);
                    string strsell = "";
                    XmlNodeList nodeCardlist = null;
                    int isellnum = 0;


                    try
                    {
                        XmlNodeList itemlist = node0.SelectNodes("itemlist");
                        if (itemlist != null)
                        {
                            foreach (XmlNode nodeitem in itemlist)
                            {
                                int id = int.Parse(nodeitem.SelectSingleNode("item_id").InnerText);
                                if (id == 202)
                                {
                                    iGuildItemCount = int.Parse(nodeitem.SelectSingleNode("num").InnerText);
                                    actionlog.Text += "收箱-卷数：" + iGuildItemCount + "\r\n";
                                }
                            }
                        }
                    }
                    catch (System.Exception ex)
                    {

                    }

                }
            }
            else
            {
                errorcount++;
                if (errorcount > 20)
                {
                    getuserid();
                }
            }
//             parameters.Clear();
//             ulr = "http://" + szhostport + "/connect/app/menu/rewardbox?cyt=1";
//             cookies = new CookieCollection();
//             c = new Cookie("S", szCookie);
//             c.Domain = szhost;
//             cookies.Add(c);
//             xml = null;
// 
//             while (true)
//             {
//                 try
//                 {
//                     xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
//                     break;
//                 }
//                 catch (System.Exception ex)
//                 {
//                     continue;
//                 }
//             }
//             if (xml != null&&xml.InnerText!="")
//             {
//                 if (int.Parse(xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("code").InnerText) != 0)
//                 {
//                     return;
//                 }
//                 XmlNode node0 = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("your_data");
//                 szCookie = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("session_id").InnerText;
//                 node0 = null;
// 
//                 XmlNodeList nodeboxs = null;
//                 try
//                 {
//                     node0 = xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("rewardbox_list");
// 
//                     nodeboxs = node0.SelectNodes("rewardbox");
//                 }
//                 catch (System.Exception ex)
//                 {
//                     return;
//                 }
//                 if (nodeboxs == null)
//                 {
//                     return;
//                 }
//                 string str = "";
//                 int i = 0;
//                 foreach (XmlNode node in nodeboxs)
//                 {
// 
//                     int itype = int.Parse(node.SelectSingleNode("type").InnerText);
// 
//                     if (itype == 2)
//                     {
//                         int id = int.Parse(node.SelectSingleNode("item_id").InnerText);
//                         if (id == 202)
//                         {
//                             i++;
//                             string str1 = node.SelectSingleNode("id").InnerText;
//                             if (str == "")
//                             {
//                                 str += str1;
//                             }
//                             else
//                             {
//                                 str += "," + str1;
//                             }
//                             if (i >= 5)
//                             {
//                                 break;
//                             }
//                         }
//                     }
//                 }
//                 if (str != "") getRewardsNoSell(str);
//                 else Thread.Sleep(60000);
                //                 cardlist = nodeCardlist = node0.SelectSingleNode("owner_card_list").SelectNodes("user_card");
                //                 actionlog.Text += "获取妖精奖励 ，总卡：" + nodeCardlist.Count + "\r\n";
        //    }
        }

        bool bgetTickt = false;
        private void ThreadGetTickt()
        {
            while (bgetTickt)
            {
                if (iGuildItemCount < 15)
                {
                    getGuildFairyRewards();
                    Thread.Sleep(60000);
                }
                else
                {
                    Thread.Sleep(60000);
                }
            }
        }

        private void getFairyRewards()
        {
            button24.Enabled = false;
            iNowUserid = getuserid();
            IDictionary<string, string> parameters = new Dictionary<string, string>()
            {
                {"",""}
            };
            parameters.Clear();
            string ulr = "http://" + szhostport + "/connect/app/menu/fairyrewards?cyt=1";
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = szhost;
            cookies.Add(c);
            XmlDocument xml = null;

            while (true)
            {
                try
                {
                    xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                    break;
                }
                catch (System.Exception ex)
                {
                    continue;
                }
            }
            if (xml != null&&xml.InnerText!="")
            {
                //                 if (int.Parse(xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("code").InnerText) != 0)
                //                 {
                //                     return 0;
                //                 }

                szCookie = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("session_id").InnerText;
                XmlNode node0 = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("your_data");
                if (node0 == null)
                {
                    button24.Enabled = true;
                    return;
                }
                szCharName = node0.SelectSingleNode("name").InnerText;
                XmlNode nodeBC = node0.SelectSingleNode("bc");
                BC = int.Parse(nodeBC.SelectSingleNode("current").InnerText);
                MaxBc = int.Parse(nodeBC.SelectSingleNode("max").InnerText);
                XmlNode nodeAP = node0.SelectSingleNode("ap");
                AP = int.Parse(nodeAP.SelectSingleNode("current").InnerText);
                MaxAP = int.Parse(nodeAP.SelectSingleNode("max").InnerText);
                string strsell = "";
                XmlNodeList nodeCardlist = null;
                int isellnum = 0;

                cardlist = nodeCardlist = node0.SelectSingleNode("owner_card_list").SelectNodes("user_card");
                actionlog.Text += "获取妖精奖励 ，总卡：" + nodeCardlist.Count + "\r\n";

            }
            button24.Enabled = true;
        }

        private int getRewards(string strr)
        {
            IDictionary<string, string> parameters = new Dictionary<string, string>()
            {
                {"",""}
            };
            parameters.Clear();
            parameters.Add("notice_id", Encrypt(strr, key12));
            string ulr = "http://" + szhostport + "/connect/app/menu/get_rewards?cyt=1";
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = szhost;
            cookies.Add(c);
            XmlDocument xml = null;

            while (true)
            {
                try
                {
                    xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                    break;
                }
                catch (System.Exception ex)
                {
                    continue;
                }
            }
            if (xml != null&&xml.InnerText!="")
            {
                //                 if (int.Parse(xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("code").InnerText) != 0)
                //                 {
                //                     return 0;
                //                 }

                szCookie = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("session_id").InnerText;
                XmlNode node0 = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("your_data");
                if (node0 == null)
                {
                    return -1;
                }
                szCharName = node0.SelectSingleNode("name").InnerText;
                XmlNode nodeBC = node0.SelectSingleNode("bc");
                BC = int.Parse(nodeBC.SelectSingleNode("current").InnerText);
                MaxBc = int.Parse(nodeBC.SelectSingleNode("max").InnerText);
                XmlNode nodeAP = node0.SelectSingleNode("ap");
                AP = int.Parse(nodeAP.SelectSingleNode("current").InnerText);
                MaxAP = int.Parse(nodeAP.SelectSingleNode("max").InnerText);
                string strsell = "";
                XmlNodeList nodeCardlist = null;
                int isellnum = 0;

                nodeCardlist = node0.SelectSingleNode("owner_card_list").SelectNodes("user_card");

                if (nodeCardlist != null && nodeCardlist.Count != 0)
                {
                    cardlist = nodeCardlist;
                    actionlog.Text += "收箱-卡数:" + nodeCardlist.Count + "\r\n";
                }
                string szSellid = "卖：\r\n";
                foreach (XmlNode nodes in nodeCardlist)
                {
                    int icardlv = int.Parse(nodes.SelectSingleNode("lv").InnerText);
                    int icardlvmax = int.Parse(nodes.SelectSingleNode("lv_max").InnerText);
                    int icardsale_price = int.Parse(nodes.SelectSingleNode("sale_price").InnerText);
                    int icardhp = int.Parse(nodes.SelectSingleNode("hp").InnerText);
                    int icardpower = int.Parse(nodes.SelectSingleNode("power").InnerText);
                    int iHolo = int.Parse(nodes.SelectSingleNode("holography").InnerText);
                    if (icardlv == 1)
                    {
                        if ((icardhp > 1 || icardpower > 1) && iHolo == 0 && icardlvmax < 50)
                        {
                            if (icardsale_price < iSellPrice)
                            {
                                if (isellnum == 0)
                                {
                                    strsell += nodes.SelectSingleNode("serial_id").InnerText;
                                }
                                else
                                {
                                    strsell += "," + nodes.SelectSingleNode("serial_id").InnerText;
                                }
                                szSellid += "ID:" + nodes.ChildNodes[1].InnerText + " lv:" + icardlv + "/" + icardlvmax + "  atk/hp:" + icardpower + "/" + icardhp + "\r\n";
                                isellnum++;
                            }
                        }
                    }
                    else if (icardlvmax < 50 && icardlv < 30)
                    {
                        if (isellnum == 0)
                        {
                            strsell += nodes.SelectSingleNode("serial_id").InnerText;
                        }
                        else
                        {
                            strsell += "," + nodes.SelectSingleNode("serial_id").InnerText;
                        }
                        szSellid += "ID:" + nodes.ChildNodes[1].InnerText + " lv:" + icardlv + "//" + icardlvmax + "  atk/hp:" + icardpower + "//" + icardhp + "\r\n";
                        isellnum++;
                    }
                    if (isellnum == 30)
                    {
                        actionlog.Text += szSellid + "\r\n";
                        if (-1 == sellcard(strsell)) return -1;
                        isellnum = 0;
                        strsell = "";
                        szSellid = "卖：\r\n";
                    }
                }
                if (strsell != "")
                {
                    actionlog.Text += szSellid;
                    if (-1 == sellcard(strsell)) return -1;
                }
            }
            return 0;
        }

        private int getRewardsNoSell(string strr)
        {
            IDictionary<string, string> parameters = new Dictionary<string, string>()
            {
                {"",""}
            };
            parameters.Clear();
            parameters.Add("notice_id", Encrypt(strr, key12));
            string ulr = "http://" + szhostport + "/connect/app/menu/get_rewards?cyt=1";
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = szhost;
            cookies.Add(c);
            XmlDocument xml = null;

            while (true)
            {
                try
                {
                    xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                    break;
                }
                catch (System.Exception ex)
                {
                    continue;
                }
            }
            if (xml != null&&xml.InnerText!="")
            {
                //                 if (int.Parse(xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("code").InnerText) != 0)
                //                 {
                //                     return 0;
                //                 }

                szCookie = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("session_id").InnerText;
                XmlNode node0 = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("your_data");
                if (node0 == null)
                {
                    return -1;
                }
                szCharName = node0.SelectSingleNode("name").InnerText;
                XmlNode nodeBC = node0.SelectSingleNode("bc");
                BC = int.Parse(nodeBC.SelectSingleNode("current").InnerText);
                MaxBc = int.Parse(nodeBC.SelectSingleNode("max").InnerText);
                XmlNode nodeAP = node0.SelectSingleNode("ap");
                AP = int.Parse(nodeAP.SelectSingleNode("current").InnerText);
                MaxAP = int.Parse(nodeAP.SelectSingleNode("max").InnerText);
                string strsell = "";
                XmlNodeList nodeCardlist = null;
                int isellnum = 0;

                try
                {
                    XmlNodeList itemlist = node0.SelectNodes("itemlist");
                    if (itemlist != null)
                    {
                        foreach (XmlNode nodeitem in itemlist)
                        {
                            int id = int.Parse(nodeitem.SelectSingleNode("item_id").InnerText);
                            if (id == 202)
                            {
                                iGuildItemCount = int.Parse(nodeitem.SelectSingleNode("num").InnerText);
                                actionlog.Text += "收箱-卷数：" + iGuildItemCount + "\r\n";
                            }
                        }
                    }
                }
                catch (System.Exception ex)
                {

                }
                try
                {
                    nodeCardlist = node0.SelectSingleNode("owner_card_list").SelectNodes("user_card");

                    if (nodeCardlist != null && nodeCardlist.Count != 0)
                    {
                        cardlist = nodeCardlist;
                        actionlog.Text += "收箱-卡数:" + nodeCardlist.Count + "\r\n";
                    }
                }
                catch (System.Exception ex)
                {

                }
            }
            return 0;
        }
        private int getRewardsAll()
        {
            IDictionary<string, string> parameters = new Dictionary<string, string>()
            {
                {"",""}
            };
            parameters.Clear();
            string ulr = "http://" + szhostport + "/connect/app/menu/rewardbox?cyt=1";
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = szhost;
            cookies.Add(c);
            XmlDocument xml = null;

            while (true)
            {
                try
                {
                    xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                    break;
                }
                catch (System.Exception ex)
                {
                    continue;
                }
            }
            if (xml != null&&xml.InnerText!="")
            {
                if (int.Parse(xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("code").InnerText) != 0)
                {
                    return -1;
                }
                szCookie = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("session_id").InnerText;
                XmlNode node0 = null;

                XmlNodeList nodeboxs = null;
                try
                {
                    node0 = xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("rewardbox_list");

                    nodeboxs = node0.SelectNodes("rewardbox");
                }
                catch (System.Exception ex)
                {
                    return -1;
                }
                if (nodeboxs == null)
                {
                    return -1;
                }
                else if (nodeboxs.Count == 0)
                {
                    return -1;
                }
                string strbox = "";
                int i = 0;
                actionlog.Text += "礼物箱" + nodeboxs.Count + "\r\n";
                foreach (XmlNode nodes in nodeboxs)
                {
                    if (i == 0)
                    {
                        strbox += nodes.SelectSingleNode("id").InnerText;
                    }
                    else
                    {
                        strbox += "," + nodes.SelectSingleNode("id").InnerText;
                    }
                    i++;
                }
                return getRewards(strbox);
            }
            return -1;
        }
        private carddeck getdeck()
        {
            carddeck newdeck = null;
            string ulr = "http://" + szhostport + "/connect/app/roundtable/edit?cyt=1";
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = szhost;
            cookies.Add(c);
            IDictionary<string, string> parameters = new Dictionary<string, string>()
                    {
                        {"",""}
                    };
            parameters.Clear();
            parameters.Add("move", Encrypt("1", key12));

            XmlDocument xml = null;
            try
            {
                xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);

            }
            catch (System.Exception ex)
            {
                return null;
            }
            if (xml != null&&xml.InnerText!="")
            {
                if (int.Parse(xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("code").InnerText) != 0)
                {
                    return null;
                }
                szCookie = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("session_id").InnerText;
                if (iServer == 1)
                {
                    newdeck = new carddeck(xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("roundtable_edit").SelectSingleNode("deck_cards").InnerText, xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("roundtable_edit").SelectSingleNode("leader_card").InnerText);
                }
                else
                    newdeck = new carddeck(xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("roundtable_edit").SelectSingleNode("deck").SelectSingleNode("deck_cards").InnerText, xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("roundtable_edit").SelectSingleNode("deck").SelectSingleNode("leader_card").InnerText);
            }


            return newdeck;
        }
        private int getuserid()
        {
            int iUserid = 0;
            string ulr = "http://" + szhostport + "/connect/app/mainmenu?cyt=1";
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = szhost;
            cookies.Add(c);
            IDictionary<string, string> parameters = new Dictionary<string, string>()
                    {
                        {"",""}
                    };
            parameters.Clear();

            XmlDocument xml = null;
            try
            {
                xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);

            }
            catch (System.Exception ex)
            {
                return 0;
            }
            if (xml != null&&xml.InnerText!="")
            {
                if (int.Parse(xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("code").InnerText) != 0)
                {
                    return 0;
                }
                szCookie = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("session_id").InnerText;
                XmlNode node0 = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("your_data");
                if (node0 == null)
                {
                    return 0;
                }
                szCharName = node0.SelectSingleNode("name").InnerText;

                XmlNode nodeBC = node0.SelectSingleNode("bc");
                BC = int.Parse(nodeBC.SelectSingleNode("current").InnerText);
                XmlNodeList itemlist = node0.SelectNodes("itemlist");
                if (itemlist != null)
                {
                    foreach (XmlNode nodeitem in itemlist)
                    {
                        int id = int.Parse(nodeitem.SelectSingleNode("item_id").InnerText);
                        if (id == 202)
                        {
                            iGuildItemCount = int.Parse(nodeitem.SelectSingleNode("num").InnerText);
                        }
                    }
                }
                MaxBc = int.Parse(nodeBC.SelectSingleNode("max").InnerText);
                XmlNode nodeAP = node0.SelectSingleNode("ap");
                AP = int.Parse(nodeAP.SelectSingleNode("current").InnerText);
                MaxAP = int.Parse(nodeAP.SelectSingleNode("max").InnerText);
                XmlNode node1 = xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("login").SelectSingleNode("user_id");
                iUserid = int.Parse(node1.InnerText);
                if (iServer == 0) iPartyid = int.Parse(node0.SelectSingleNode("party_id").InnerText);
                iuserLevel = int.Parse(node0.SelectSingleNode("town_level").InnerText);
                actionlog.Text += "登录成功\r\ncookie:" + szCookie + "|user:" + iUserid.ToString() + "|name:" + szCharName + "\r\n";
            }
            return iUserid;
        }
        private int getapbc()
        {
            if (iAreaID == 0)
            {
                GetAreaIfo();
            }
            IDictionary<string, string> parameters = new Dictionary<string, string>()
            {
                {"",""}
            };
            parameters.Clear();
            string s1 = "1";
            parameters.Add("area_id", Encrypt(iAreaID.ToString(), key12));
            parameters.Add("check", Encrypt(s1.ToString(), key12));
            parameters.Add("floor_id", Encrypt(szFloor.ToString(), key12));
            string ulr = "http://" + szhostport + "/connect/app/exploration/get_floor?cyt=1";
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = szhost;
            cookies.Add(c);
            XmlDocument xml = null;

            while (true)
            {
                try
                {
                    xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                    break;
                }
                catch (System.Exception ex)
                {
                    continue;
                }
            }
            if (xml != null&&xml.InnerText!="")
            {
                if (int.Parse(xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("code").InnerText) != 0)
                {
                    //                     if (bAutoChange)
                    //                     {
                    //                         iAreaID--;
                    //                         szFloor = "1";
                    //                         bAutoChange = false;
                    //                     }
                    //                     else
                    //                     {
                    //                         iAreaID = 0;
                    //                         szFloor = "1";
                    //                     }
                    return 0;
                }
                szCookie = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("session_id").InnerText;
                XmlNode node0 = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("your_data"); szCharName = node0.SelectSingleNode("name").InnerText;

                XmlNode nodeBC = node0.SelectSingleNode("bc");
                BC = int.Parse(nodeBC.SelectSingleNode("current").InnerText);

                MaxBc = int.Parse(nodeBC.SelectSingleNode("max").InnerText);
                XmlNode nodeAP = node0.SelectSingleNode("ap");
                AP = int.Parse(nodeAP.SelectSingleNode("current").InnerText);
                MaxAP = int.Parse(nodeAP.SelectSingleNode("max").InnerText);
                XmlNode node1 = xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("get_floor");
                ilowap = int.Parse(node1.SelectSingleNode("floor_info").SelectSingleNode("cost").InnerText);
                AreaName = node1.SelectSingleNode("area_name").InnerText;

                XmlNode nodeg = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("guild_fairy_state");
                int ire = 0;
                if (nodeg != null)
                {
                    ire = int.Parse(nodeg.SelectSingleNode("fairy_state").InnerText);
                }
                return ire;
            }
            else
            {
                return 0;
            }
        }


        private void useitem(int iD)
        {
            IDictionary<string, string> parameters = new Dictionary<string, string>()
            {
                {"",""}
            };
            parameters.Clear();
            parameters.Add("item_id", Encrypt(iD.ToString(), key12));
            string ulr = "http://" + szhostport + "/connect/app/item/use?cyt=1";
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = szhost;
            cookies.Add(c);
            XmlDocument xml = null;

            while (true)
            {
                try
                {
                    xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                    break;
                }
                catch (System.Exception ex)
                {
                    continue;
                }
            }
            if (xml != null&&xml.InnerText!="")
            {
                try
                {
                    if (int.Parse(xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("code").InnerText) != 0)
                    {
                        //GetAreaIfo();
                        string errormessage = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("message").InnerText + "\r\n";
                        actionlog.Text += "[" + DateTime.Now.ToString() + "]" + errormessage; actionlog.WriteInfo(errormessage);

                    }
                    szCookie = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("session_id").InnerText;
                    XmlNode node0 = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("your_data"); szCharName = node0.SelectSingleNode("name").InnerText;
                    XmlNode nodeBC = node0.SelectSingleNode("bc");
                    BC = int.Parse(nodeBC.SelectSingleNode("current").InnerText);
                    MaxBc = int.Parse(nodeBC.SelectSingleNode("max").InnerText);
                    XmlNode nodeAP = node0.SelectSingleNode("ap");
                    AP = int.Parse(nodeAP.SelectSingleNode("current").InnerText);
                    MaxAP = int.Parse(nodeAP.SelectSingleNode("max").InnerText);


                }
                catch (System.Exception ex)
                {
                    actionlog.Text += "[" + DateTime.Now.ToString() + "]" + ex.Message + "\r\n"; actionlog.WriteInfo(ex.Message + "\r\n");
                }
            }
        }
        bool bAtoBuild = true;
        int imaicount = 0;

        private int explore_1()
        {
            int iRe = -1;
            int ire = 0;
            if (iAreaID == 0)
            {
                GetAreaIfo();
            }
            IDictionary<string, string> parameters = new Dictionary<string, string>()
            {
                {"",""}
            };
            parameters.Clear();
            bAtoBuild = checkBox7.Checked;
            string s1 = bAtoBuild ? "1" : "0";
            parameters.Add("area_id", Encrypt(iAreaID.ToString(), key12));
            parameters.Add("auto_build", Encrypt(s1.ToString(), key12));
            parameters.Add("floor_id", Encrypt(szFloor, key12));
            string ulr = "http://" + szhostport + "/connect/app/exploration/explore?cyt=1";
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = szhost;
            cookies.Add(c);
            XmlDocument xml = null;

            while (true)
            {
                try
                {
                    xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                    break;
                }
                catch (System.Exception ex)
                {
                    continue;
                }
            }
            if (xml != null&&xml.InnerText!="")
            {
                string szLogTemp = "移动：";
                try
                {
                    XmlNode ereaNode = xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("exploration_area");
                    if (Properties.Settings.Default.xmlsave)xml.Save("explore1.xml");
                    if (ereaNode != null)
                    {
                        if (!bliqu) return ire;
                        XmlNodeList erarlist = ereaNode.SelectSingleNode("area_info_list").SelectNodes("area_info");
                        iAreaID = int.Parse(erarlist[0].SelectSingleNode("id").InnerText);
                        AreaName = erarlist[0].SelectSingleNode("name").InnerText;
                        if (!bAutoChange)
                        {
                            foreach (XmlNode enodes in erarlist)
                            {
                                int inowid = int.Parse(enodes.SelectSingleNode("id").InnerText);
                                if (iAreaID / 100 == inowid / 100)
                                {
                                    iAreaID = inowid;
                                    AreaName = enodes.SelectSingleNode("name").InnerText;
                                }
                            }
                        }
                        szFloor = "1";
                        szLogTemp += "里表区切换 ; ";
                        if (int.Parse(xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("code").InnerText) != 0)
                        {
                            //GetAreaIfo();
                            szLogTemp += xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("message").InnerText + "\r\n";

                        }

                        actionlog.Text += "[" + DateTime.Now.ToString() + "]" + szLogTemp; actionlog.WriteInfo(szLogTemp);

                        return ire;
                    }
                    if (int.Parse(xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("code").InnerText) != 0)
                    {
                        //GetAreaIfo();
                        szLogTemp += xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("message").InnerText + "\r\n";
                        actionlog.Text += "[" + DateTime.Now.ToString() + "]" + szLogTemp; actionlog.WriteInfo(szLogTemp);

                        return ire;
                    }
                    szCookie = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("session_id").InnerText;
                    XmlNode node0 = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("your_data"); szCharName = node0.SelectSingleNode("name").InnerText;
                    XmlNode nodeBC = node0.SelectSingleNode("bc");
                    int oldAp = AP;
                    int oldBC = BC;
                    BC = int.Parse(nodeBC.SelectSingleNode("current").InnerText);
                    MaxBc = int.Parse(nodeBC.SelectSingleNode("max").InnerText);
                    XmlNode nodeAP = node0.SelectSingleNode("ap");
                    AP = int.Parse(nodeAP.SelectSingleNode("current").InnerText);
                    MaxAP = int.Parse(nodeAP.SelectSingleNode("max").InnerText);
                    iRe = int.Parse(xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("explore").SelectSingleNode("event_type").InnerText);

                    int iPorgress = int.Parse(xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("explore").SelectSingleNode("progress").InnerText);
                    //((ComboBoxItem)comboBox3.SelectedItem).Text = "区域" + szFloor + "|" + ilowap.ToString() + "|" + iPorgress.ToString();
                    XmlNode nodecard = node0.SelectSingleNode("owner_card_list");
                    if (nodecard != null)
                    {
                        XmlNodeList xmllist = nodecard.SelectNodes("user_card");
                        if (xmllist.Count != 0)
                            cardlist = xmllist;
                    }
                    XmlNode nodeg = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("guild_fairy_state");

                    if (nodeg != null)
                    {
                        ire = int.Parse(nodeg.SelectSingleNode("fairy_state").InnerText);
                    }
                    szLogTemp += AreaName + "|" + szFloor + "|" + ilowap + "|" + iPorgress + "-";
                    string szBoss = "";
                    if (iRe == 1)
                    {
                        while (bAting) Thread.Sleep(1000);
                        bExplore = false;
                        bAting = true;
                        getFairyIfo();
                        bAting = false;
                        XmlNode fairyNode = xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("explore").SelectSingleNode("fairy");
                        iMasterBossID = int.Parse(fairyNode.SelectSingleNode("serial_id").InnerText);

                        szBoss = "lv" + fairyNode.SelectSingleNode("lv").InnerText + fairyNode.SelectSingleNode("name").InnerText + " HP:" + fairyNode.SelectSingleNode("hp").InnerText;
                    }

                    switch (iRe)
                    {
                        case 1:
                            szLogTemp += "发现妖精" + szBoss;
                            break;
                        case 3:
                            szLogTemp += "发现卡片";
                            break;
                        case 15:
                            szLogTemp += "合成卡片";
                            break;
                        case 6:
                            szLogTemp += "AP不足";
                            break;
                        case 12:
                            szLogTemp += "AP回复";
                            break;
                        case 13:
                            szLogTemp += "BC回复";
                            break;
                        case 19:
                            szLogTemp += "发现道具";
                            break;
                        default:
                            szLogTemp += "事件ID:" + iRe.ToString();
                            break;
                    }
                    szLogTemp += "  AP:" + oldAp.ToString() + "-" + AP.ToString() + " BC:" + oldBC.ToString() + "-" + BC.ToString() + "\r\n";
                    actionlog.Text += "[" + DateTime.Now.ToString() + "]" + szLogTemp; actionlog.WriteInfo(szLogTemp);

                    if (iPorgress == 100)
                    {
                        XmlNode nodenext = xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("explore").SelectSingleNode("next_floor");
                        if (nodenext != null && comboBox3.SelectedIndex == comboBox3.Items.Count - 1)
                        {
                            GetFloorIfo();
                            comboBox3.SelectedIndex = comboBox3.Items.Count - 2;
                        }
                        if (bAutoChange)
                        {
                            if (nodenext != null)
                            {
                                comboBox3.SelectedIndex = comboBox3.Items.Count - 1;
                            }
                            else
                            {
                                GetAreaIfo();
                            }
                        }
                    }
                }
                catch (System.Exception ex)
                {
                    szLogTemp += ex.Message + "\r\n";
                    actionlog.Text += "[" + DateTime.Now.ToString() + "]" + szLogTemp; actionlog.WriteInfo(szLogTemp);
                }

            }
            return iRe;
        }
        int iuserLevel = 0;
        private int explore()
        {
            int iRe = -1;
            int ire = 0;
            if (iAreaID == 0)
            {
                GetAreaIfo();
            }
            IDictionary<string, string> parameters = new Dictionary<string, string>()
            {
                {"",""}
            };
            parameters.Clear();
            string s1 = bAtoBuild ? "1" : "0";
            parameters.Add("area_id", Encrypt(iAreaID.ToString(), key12));
            parameters.Add("auto_build", Encrypt(s1.ToString(), key12));
            parameters.Add("floor_id", Encrypt(szFloor, key12));
            string ulr = "http://" + szhostport + "/connect/app/exploration/guild_explore?cyt=1";
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = szhost;
            cookies.Add(c);
            XmlDocument xml = null;

            int oldAp = AP;
            int oldBC = BC;
            while (true)
            {
                try
                {
                    xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                    break;
                }
                catch (System.Exception ex)
                {
                    continue;
                }
            }
            if (xml != null&&xml.InnerText!="")
            {
                if (Properties.Settings.Default.xmlsave)xml.Save("explore.xml");
                string szLogTemp = "移动：";
                try
                {
                    XmlNode ereaNode = xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("exploration_area");
                    if (ereaNode != null)
                    {
                        if (!bliqu) return ire;
                        XmlNodeList erarlist = ereaNode.SelectSingleNode("area_info_list").SelectNodes("area_info");
                        iAreaID = int.Parse(erarlist[0].SelectSingleNode("id").InnerText);
                        AreaName = erarlist[0].SelectSingleNode("name").InnerText;
                        if (!bAutoChange)
                        {
                            foreach (XmlNode enodes in erarlist)
                            {
                                int inowid = int.Parse(enodes.SelectSingleNode("id").InnerText);
                                if (iAreaID / 100 == inowid / 100)
                                {
                                    iAreaID = inowid;
                                    AreaName = enodes.SelectSingleNode("name").InnerText;
                                }
                            }
                        }
                        //szFloor = "1";
                        GetFloorIfo();
                        szLogTemp += "里表区切换 ; ";
                        if (int.Parse(xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("code").InnerText) != 0)
                        {
                            //GetAreaIfo();
                            szLogTemp += xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("message").InnerText + "\r\n";

                        }

                        actionlog.Text += "[" + DateTime.Now.ToString() + "]" + szLogTemp; actionlog.WriteInfo(szLogTemp);

                        return ire;
                    }
                    if (int.Parse(xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("code").InnerText) != 0)
                    {
                        //GetAreaIfo();
                        szLogTemp += xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("message").InnerText + "\r\n";
                        actionlog.Text += "[" + DateTime.Now.ToString() + "]" + szLogTemp; actionlog.WriteInfo(szLogTemp);

                        return ire;
                    }

                    iRe = int.Parse(xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("explore").SelectSingleNode("event_type").InnerText);
                    

                    szCookie = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("session_id").InnerText;
                    XmlNode node0 = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("your_data"); 
                    szCharName = node0.SelectSingleNode("name").InnerText;
                    XmlNode nodeBC = node0.SelectSingleNode("bc");
                    BC = int.Parse(nodeBC.SelectSingleNode("current").InnerText);
                    MaxBc = int.Parse(nodeBC.SelectSingleNode("max").InnerText);
                    XmlNode nodeAP = node0.SelectSingleNode("ap");
                    AP = int.Parse(nodeAP.SelectSingleNode("current").InnerText);
                    MaxAP = int.Parse(nodeAP.SelectSingleNode("max").InnerText);
                    int itown_lv = int.Parse(node0.SelectSingleNode("town_level").InnerText);
                    if (iuserLevel != itown_lv)
                    {
                        iuserLevel = itown_lv;
                        actionlog.Text += "升级：Lv" + iuserLevel + "\r\n";
                        bxiap = true;
                        //setbc();
                    }
                    int iPorgress = int.Parse(xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("explore").SelectSingleNode("progress").InnerText);
                    //((ComboBoxItem)comboBox3.SelectedItem).Text = "区域" + szFloor + "|" + ilowap.ToString() + "|" + iPorgress.ToString();
                    XmlNode nodecard = node0.SelectSingleNode("owner_card_list");
                    if (nodecard != null)
                    {
                        XmlNodeList xmllist = nodecard.SelectNodes("user_card");
                        if (xmllist.Count != 0)
                            cardlist = xmllist;
                    }
                    XmlNode nodeg = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("guild_fairy_state");

                    if (nodeg != null)
                    {
                        ire = int.Parse(nodeg.SelectSingleNode("fairy_state").InnerText);
                    }
                    szLogTemp += AreaName + "|" + szFloor + "|" + ilowap + "|" + iPorgress + "-";
                    

                    switch (iRe)
                    {
                        case 1:
                            szLogTemp += "发现妖精";
                            break;
                        case 3:
                            szLogTemp += "发现卡片";
                            break;
                        case 15:
                            szLogTemp += "合成卡片";
                            break;
                        case 6:
                            szLogTemp += "AP不足";
                            break;
                        case 12:
                            szLogTemp += "AP回复";
                            break;
                        case 13:
                            szLogTemp += "BC回复";
                            break;
                        case 19:
                            szLogTemp += "发现道具";
                            break;
                        default:
                            szLogTemp += "事件ID:" + iRe.ToString();
                            break;
                    }
                    szLogTemp += "  AP:" + oldAp.ToString() + "-" + AP.ToString() + " BC:" + oldBC.ToString() + "-" + BC.ToString() + "\r\n";
                    actionlog.Text += "[" + DateTime.Now.ToString() + "]" + szLogTemp; actionlog.WriteInfo(szLogTemp);
//                     if (iRe == 1)
//                     {
//                         getGuidIFO();
//                         ire = 65;
//                     }

                    if (iRe == 1 || iRe == 22)
                    {
                        actionlog.Text += "发现妖精:";
                        try
                        {
                            XmlNode fairyNode = xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("explore").SelectSingleNode("ex_fairy").SelectSingleNode("fairy");
                            iMasterBossID = int.Parse(fairyNode.SelectSingleNode("serial_id").InnerText);

                            actionlog.Text += "lv" + fairyNode.SelectSingleNode("lv").InnerText + fairyNode.SelectSingleNode("name").InnerText + " HP:" + fairyNode.SelectSingleNode("hp").InnerText + "\r\n";

                        }
                        catch (System.Exception ex)
                        {
                            actionlog.Text += "\r\n";
                        }
                        while (bAting) Thread.Sleep(1000);
                        bExplore = false;
                        bAting = true;
                        getGuildFairyIfo();
                        bAting = false;
                    }
                    if (iPorgress == 100)
                    {
                        XmlNode nodenext = xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("explore").SelectSingleNode("next_floor");
                        if (nodenext != null && comboBox3.SelectedIndex == comboBox3.Items.Count - 1)
                        {
                            GetFloorIfo();
                            comboBox3.SelectedIndex = comboBox3.Items.Count - 2;
                        }
                        if (bAutoChange)
                        {
                            if (nodenext != null)
                            {
                                comboBox3.SelectedIndex = comboBox3.Items.Count - 1;
                            }
                            else
                            {
                                GetAreaIfo();
                            }
                        }
                    }
                }
                catch (System.Exception ex)
                {
                    szLogTemp += ex.Message + "\r\n";
                    actionlog.Text += "[" + DateTime.Now.ToString() + "]" + szLogTemp; actionlog.WriteInfo(szLogTemp);
                }

            }
            return ire;
        }

        private void MessageBox(string p)
        {
            throw new NotImplementedException();
        }

        private void UpdateJob()
        {
            string ulr = "http://" + szhostport + "/connect/app/job/job_top?cyt=1";
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = szhost;
            cookies.Add(c);
            XmlDocument xml = null;

            actionlog.Text += "更新职业\r\n";
            while (true)
            {
                try
                {
                    xml = CreatePostHttpResponse(ulr, null, (int?)50000, string.Empty, Encoding.Default, cookies);
                    break;
                }
                catch (System.Exception ex)
                {
                    continue;
                }
            }
            areaxml = xml;
            if (xml != null&&xml.InnerText!="")
            {
                XmlNode node1 = xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("job_top");
                XmlNodeList jobs = node1.SelectNodes("job_states");
                iJobID = int.Parse(node1.SelectSingleNode("equipping_job_id").InnerText);
                comboBox2.Items.Clear();
                ComboBoxItem cbis = null;
                int iindex = 0;
                foreach (XmlNode nodes in jobs)
                {
                    int id = int.Parse(nodes.SelectSingleNode("job_id").InnerText);
                    int lv = int.Parse(nodes.SelectSingleNode("job_lv").InnerText);
                    string szname;
                    switch (id)
                    {
                        case 1:
                            szname = "士兵|" + lv;
                            break;
                        case 2:
                            szname = "武斗|" + lv;
                            break;
                        case 3:
                            szname = "操纵|" + lv;
                            break;
                        case 4:
                            szname = "弓手|" + lv;
                            break;
                        case 5:
                            szname = "风水|" + lv;
                            break;
                        case 6:
                            szname = "曜魔|" + lv;
                            break;
                        case 7:
                            szname = "会长|" + lv;
                            break;
                        case 8:
                            szname = "妹|" + lv;
                            break;
                        case 9:
                            szname = "雀鬼|" + lv;
                            break;
                        default:
                            szname = "??|" + lv;
                            break;
                    }

                    actionlog.Text += szname + "、";
                    ComboBoxItem cbi = new ComboBoxItem();
                    cbi.Value = id;
                    cbi.Text = szname;
                    comboBox2.Items.Add(cbi);
                    if (id == iJobID)
                    {
                        comboBox2.SelectedIndex = iindex;
                    }
                    iindex++;
                    //                     if (id != 0 && id != 50002 && id != 50004 && id != 50005)
                    //                     {
                    //                         AreaName = nodes.SelectSingleNode("name").InnerText;
                    //                         iAreaID = id;
                    //                     }
                }
                actionlog.Text += "\r\n";
            }
        }

        private void GetFloorIfo()
        {
            IDictionary<string, string> parameters = new Dictionary<string, string>()
            {
                {"",""}
            };
            parameters.Clear();
            parameters.Add("area_id", Encrypt(iAreaID.ToString(), key12));
            string ulr = "http://" + szhostport + "/connect/app/exploration/floor?cyt=1";
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = szhost;
            cookies.Add(c);
            XmlDocument xml = null;

            actionlog.Text += "更新层数\r\n";
            while (true)
            {
                try
                {
                    xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                    break;
                }
                catch (System.Exception ex)
                {
                    continue;
                }
            }
            areaxml = xml;
            if (xml != null&&xml.InnerText!="")
            {
                XmlNode node1 = xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("exploration_floor").SelectSingleNode("floor_info_list");
                comboBox3.Items.Clear();
                foreach (XmlNode nodes in node1.ChildNodes)
                {
                    try
                    {
                        int id = int.Parse(nodes.SelectSingleNode("id").InnerText);
                        int cost = int.Parse(nodes.SelectSingleNode("cost").InnerText);
                        int progress = int.Parse(nodes.SelectSingleNode("progress").InnerText);

                        ComboBoxItem cbi = new ComboBoxItem();
                        cbi.Value = id;
                        cbi.Text = "区域" + id.ToString() + "|" + cost.ToString() + "|" + progress.ToString();
                        comboBox3.Items.Add(cbi);
                    }
                    catch (System.Exception ex)
                    {

                    }
                }
                if (comboBox3.Items.Count > 0)
                {
                    comboBox3.SelectedIndex = 0;
                }
            }
        }
        private void GetAreaIfo()
        {
            string ulr = "http://" + szhostport + "/connect/app/exploration/area?cyt=1";
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = szhost;
            cookies.Add(c);
            XmlDocument xml = null;

            actionlog.Text += "更新地图\r\n";
            while (true)
            {
                try
                {
                    xml = CreatePostHttpResponse(ulr, null, (int?)50000, string.Empty, Encoding.Default, cookies);
                    break;
                }
                catch (System.Exception ex)
                {
                    continue;
                }
            }
            areaxml = xml;
            if (xml != null&&xml.InnerText!="")
            {
                XmlNode node1 = xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("exploration_area").SelectSingleNode("area_info_list");
                comboBox1.Items.Clear();
                foreach (XmlNode nodes in node1.ChildNodes)
                {
                    XmlNode node2 = nodes.SelectSingleNode("area_type");
                    if (node2.InnerText == "0")
                    {
                        break;
                    }
                    int id = int.Parse(nodes.SelectSingleNode("id").InnerText);

                    ComboBoxItem cbi = new ComboBoxItem();
                    cbi.Value = id;
                    cbi.Text = nodes.SelectSingleNode("name").InnerText;
                    comboBox1.Items.Add(cbi);
                    //                     if (id != 0 && id != 50002 && id != 50004 && id != 50005)
                    //                     {
                    //                         AreaName = nodes.SelectSingleNode("name").InnerText;
                    //                         iAreaID = id;
                    //                     }
                }
                if (comboBox1.Items.Count > 0)
                {
                    comboBox1.SelectedIndex = 0;
                }
            }
            actionlog.Text += "更新成功\r\n";
        }

        int ibuyCount = 0;

        private void buy(int iProduct, int icount)
        {
            IDictionary<string, string> parameters = new Dictionary<string, string>()
                {
                    {"",""}
                };
            string ulr = "http://" + szhostport + "/connect/app/gacha/buy?cyt=1";
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = szhost;
            cookies.Add(c);
            XmlDocument xml = null;
            while (true)
                try
                {
                    parameters.Clear();
                    parameters.Add("auto_build", Encrypt("0", key12));
                    parameters.Add("bulk", Encrypt("0", key12));
                    parameters.Add("product_id", Encrypt(iProduct.ToString(), key12));
                    xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                    break;
                }
                catch (System.Exception ex)
                {

                }
            if (xml != null&&xml.InnerText!="")
            {
                if (int.Parse(xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("code").InnerText) != 0)
                {
                    ibuyCount = 0;
                    return;
                }
                else
                {
                    szCookie = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("session_id").InnerText;
                    XmlNode node0 = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("your_data"); szCharName = node0.SelectSingleNode("name").InnerText + "正在挂机";
                    XmlNode nodeBC = node0.SelectSingleNode("bc");
                    BC = int.Parse(nodeBC.SelectSingleNode("current").InnerText);
                    MaxBc = int.Parse(nodeBC.SelectSingleNode("max").InnerText);
                    XmlNode nodeAP = node0.SelectSingleNode("ap");
                    AP = int.Parse(nodeAP.SelectSingleNode("current").InnerText);
                    MaxAP = int.Parse(nodeAP.SelectSingleNode("max").InnerText);
                    string strsell = "";
                    XmlNodeList nodeCardlist = null;
                    int isellnum = 0;

                    nodeCardlist = node0.SelectSingleNode("owner_card_list").SelectNodes("user_card");

                    string szLogTemp = "抽卡：ID:" + nodeCardlist[0].ChildNodes[1].InnerText + "\r\n"; ;
                    actionlog.Text += "[" + DateTime.Now.ToString() + "]" + szLogTemp;
                    string szSellid = "";
                    if (ibuyCount <= icount)
                    {
                        ibuyCount++;
                        if (nodeCardlist.Count < 190) buy(iProduct, icount);
                        return;
                    }
                    foreach (XmlNode nodes in nodeCardlist)
                    {
                        int icardlv = int.Parse(nodes.SelectSingleNode("lv").InnerText);
                        int icardlvmax = int.Parse(nodes.SelectSingleNode("lv_max").InnerText);
                        int icardsale_price = int.Parse(nodes.SelectSingleNode("sale_price").InnerText);
                        int icardhp = int.Parse(nodes.SelectSingleNode("hp").InnerText);
                        int icardpower = int.Parse(nodes.SelectSingleNode("power").InnerText);
                        int iHolo = int.Parse(nodes.SelectSingleNode("holography").InnerText);
                        if (icardlv == 1)
                        {
                            if ((icardhp > 1 || icardpower > 1) && iHolo == 0 && icardlvmax < 50)
                            {
                                if (icardsale_price < iSellPrice)
                                {
                                    if (isellnum == 0)
                                    {
                                        strsell += nodes.SelectSingleNode("serial_id").InnerText;
                                    }
                                    else
                                    {
                                        strsell += "," + nodes.SelectSingleNode("serial_id").InnerText;
                                    }
                                    szSellid += "ID:" + nodes.ChildNodes[1].InnerText + " lv:" + icardlv + "/" + icardlvmax + "  atk/hp:" + icardpower + "/" + icardhp + "\r\n";
                                    isellnum++;
                                }
                            }
                        }
                        else if (icardlvmax < 50 && icardlv < 30)
                        {
                            if (isellnum == 0)
                            {
                                strsell += nodes.SelectSingleNode("serial_id").InnerText;
                            }
                            else
                            {
                                strsell += "," + nodes.SelectSingleNode("serial_id").InnerText;
                            }
                            szSellid += "ID:" + nodes.ChildNodes[1].InnerText + " lv:" + icardlv + "//" + icardlvmax + "  atk/hp:" + icardpower + "//" + icardhp + "\r\n";
                            isellnum++;
                        }
                        if (isellnum == 30)
                        {
                            actionlog.Text += szSellid + "\r\n";
                            if (-1 == sellcard(strsell))
                            {
                                ibuyCount = 0;
                                return;
                            }
                            isellnum = 0;
                            strsell = "";
                            szSellid = "卖：\r\n";
                        }
                    }
                    if (strsell != "")
                    {
                        actionlog.Text += szSellid;

                        if (-1 == sellcard(strsell))
                        {
                            ibuyCount = 0;
                            return;
                        }
                    }
                    ibuyCount = 0;
                    buy(iProduct, icount);

                }
            }
        }
        int inowcard = -1;
        private void ChangeCard(int inum,int scardnum)
        {
            if (inowcard == inum)
            {
                return;
            }

            carddeck cd = cardset.getdeck(inum);
            if (cd == null)
            {
                return;
            }
            string szcard = cd.ToString();
            string szleader = cd.getLeader();
            IDictionary<string, string> parameters = new Dictionary<string, string>()
                {
                    {"",""}
                };
            parameters.Clear();

            parameters.Add("C", Encrypt(szcard, key12));
            parameters.Add("lr", Encrypt(szleader, key12));
            parameters.Add("no", Encrypt(scardnum.ToString(), key12));


            string ulr = "http://" + szhostport + "/connect/app/cardselect/savedeckcard?cyt=1";
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = szhost;
            cookies.Add(c);
            XmlDocument xml = null;

            while (true)
            {
                try
                {
                    xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                    break;
                }
                catch (System.Exception ex)
                {
                    continue;
                }
            }
            inowcard = inum;
            szCookie = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("session_id").InnerText;
            actionlog.Text += "[" + DateTime.Now.ToString() + "]" + "换卡：" + cd.name + "\r\n";
            actionlog.WriteInfo("换卡："+scardnum +"-" + cd.name + "\r\n");
        }
        private void ChangeCard(int inum)
        {
            if (inowcard == inum)
            {
                return;
            }

            carddeck cd = cardset.getdeck(inum);
            if (cd == null)
            {
                return;
            }
            string szcard = cd.ToString();
            string szleader = cd.getLeader();
            IDictionary<string, string> parameters = new Dictionary<string, string>()
                {
                    {"",""}
                };
            parameters.Clear();

            parameters.Add("C", Encrypt(szcard, key12));
            parameters.Add("lr", Encrypt(szleader, key12));


            string ulr = "http://" + szhostport + "/connect/app/cardselect/savedeckcard?cyt=1";
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = szhost;
            cookies.Add(c);
            XmlDocument xml = null;

            while (true)
            {
                try
                {
                    xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                    break;
                }
                catch (System.Exception ex)
                {
                    continue;
                }
            }
            inowcard = inum;
            szCookie = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("session_id").InnerText;
            actionlog.Text += "[" + DateTime.Now.ToString() + "]" + "换卡：" + cd.name + "\r\n";
            actionlog.WriteInfo("换卡：" + cd.name + "\r\n");
        }
        private void ChangeCard(string szcard, string szleader)
        {
            IDictionary<string, string> parameters = new Dictionary<string, string>()
                {
                    {"",""}
                };
            parameters.Clear();

            parameters.Add("C", Encrypt(szcard, key12));
            parameters.Add("lr", Encrypt(szleader, key12));


            string ulr = "http://" + szhostport + "/connect/app/cardselect/savedeckcard?cyt=1";
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = szhost;
            cookies.Add(c);
            XmlDocument xml = null;

            while (true)
            {
                try
                {
                    xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                    break;
                }
                catch (System.Exception ex)
                {
                    continue;
                }
            }
            szCookie = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("session_id").InnerText;
            actionlog.Text += "[" + DateTime.Now.ToString() + "]" + "换卡：" + szleader + "\r\n";
            actionlog.WriteInfo("换卡：" + szleader + "\r\n");

        }

        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            textBox2.Enabled = radioButton1.Checked;
            textBox3.Enabled = radioButton2.Checked;
            LoginType = radioButton1.Checked ? 0 : 1;
        }

        private void radioButton2_CheckedChanged(object sender, EventArgs e)
        {
            textBox2.Enabled = radioButton1.Checked;
            textBox3.Enabled = radioButton2.Checked;
            LoginType = radioButton1.Checked ? 0 : 1;
        }
        void EnableLoint(bool blogin)
        {
            if (!blogin)
            {
                textBox1.Enabled = false;
                textBox2.Enabled = false;
                textBox3.Enabled = false;
                button1.Enabled = false;
                button2.Enabled = true;
                radioButton8.Enabled = false;
                radioButton10.Enabled = false;
            }
            else
            {
                textBox1.Enabled = true;
                radioButton1.Enabled = true;
                radioButton2.Enabled = true;
                textBox2.Enabled = radioButton1.Checked;
                textBox3.Enabled = radioButton2.Checked;
                LoginType = radioButton1.Checked ? 0 : 1;
                button2.Enabled = false;
                button1.Enabled = true;
                radioButton8.Enabled = true;
                radioButton10.Enabled = true;
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            MainThread = new Thread(threadMain);
            MainThread.Start();
            EnableLoint(false);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            bLogin = false;
            button3.Enabled = false;
            button4.Enabled = false;
            button5.Enabled = false;
            button6.Enabled = false;
            button7.Enabled = false;
            button8.Enabled = false;
            button9.Enabled = false;
            button10.Enabled = false;
            button11.Enabled = false;
            button12.Enabled = false;
            button13.Enabled = false;
            button14.Enabled = false;
            button15.Enabled = false;
            button16.Enabled = false;
            button17.Enabled = false;
            button18.Enabled = false;
            button20.Enabled = false;
            button21.Enabled = false;
            button22.Enabled = false;
            button23.Enabled = false;
            button24.Enabled = false;
            button25.Enabled = false;
            button26.Enabled = false;
            button27.Enabled = false;
            radioButton8.Enabled = true;
            radioButton10.Enabled = true;
            closeThread();
            EnableLoint(true);
        }
        private void closeThread()
        {

            if (bThreadAttack)
            {
                bThreadAttack = false;
                Thread.Sleep(1000);
                AttackThread.Abort();
            }
            if (bThreadMain)
            {
                bThreadMain = false;
                Thread.Sleep(1000);
                MainThread.Abort();
            }
            if (bThreadRank)
            {
                bThreadRank = false;
                Thread.Sleep(1000);
                RankThread.Abort();
            }
            if (bThreadExplore)
            {
                bThreadExplore = false;
                Thread.Sleep(1000);
                ExploreThread.Abort();
            }
            if (bThreadRigist)
            {
                bNoLimitedBC = false;
                Thread.Sleep(1000);
                RigistThread.Abort();
            }
            if (bThreadEx)
            {
                bThreadEx = false;
                Thread.Sleep(1000);
                ExThread.Abort();
            }
        }
        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            closeThread();
        }
        int iTIME = 0;
        
        private void timer1_Tick(object sender, EventArgs e)
        {
            //             if (textBoxLog.Text != szActionLog)
            //             {
            //                 //textBoxLog.Text = szActionLog;
            //                 //actionlog.Text = szActionLog;

            //             }
            iTIME++;
            //if (iTIME > 100 && bThreadAttack)
            //{
            //    getGuidIFO();
            //    iTIME = 0;
            //}
            this.Text ="MillionHentai4"+ "(BC:" + BC + "/" + MaxBc + "AP:" + AP + "/" + MaxAP+")";
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBox1.Items != null && comboBox1.Items.Count > 0 && comboBox1.SelectedItem != null)
            {
                string text = ((ComboBoxItem)comboBox1.SelectedItem).Text;
                object vlaue = ((ComboBoxItem)comboBox1.SelectedItem).Value;
                AreaName = text;
                iAreaID = (int)vlaue;
                GetFloorIfo();
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            MapsEvent.BeginInvoke(null, EventArgs.Empty, null, null);
        }

        private void button4_Click(object sender, EventArgs e)
        {
            Thread ranktread = new Thread(partyrank);
            ranktread.Start();
        }

        private void button5_Click(object sender, EventArgs e)
        {
            RewardsEvent.BeginInvoke(null, EventArgs.Empty, null, null);
            button5.Enabled = false;
        }
        int ichose = 0;
        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBox2.Items != null && comboBox2.Items.Count > 0 && comboBox2.SelectedItem != null)
            {
                string text = ((ComboBoxItem)comboBox2.SelectedItem).Text;
                object vlaue = ((ComboBoxItem)comboBox2.SelectedItem).Value;
                changejob((int)vlaue);
                ichose = (int)vlaue;
            }
        }

        private void button6_Click(object sender, EventArgs e)
        {
            UpdateJob();
        }

        private void comboBox3_SelectedIndexChanged(object sender, EventArgs e)
        {

            if (comboBox3.Items != null && comboBox3.Items.Count > 0 && comboBox3.SelectedItem != null)
            {
                string text = ((ComboBoxItem)comboBox3.SelectedItem).Text;
                object vlaue = ((ComboBoxItem)comboBox3.SelectedItem).Value;
                szFloor = vlaue.ToString();
            }
        }

        private void button6_Click_1(object sender, EventArgs e)
        {
            if (!bThreadExplore)
            {
                bThreadExplore = true;
                ExploreThread = new Thread(threadExplore);
                ExploreThread.Start();
                button6.Text = "停止跑图";
            }
            else
            {
                bThreadExplore = false;
                Thread.Sleep(1000);
                ExploreThread.Abort();
                button6.Text = "挂机跑图";
            }
        }

        private void button7_Click(object sender, EventArgs e)
        {
            //ExploreEvent.BeginInvoke(null, EventArgs.Empty, null, null);
            Form2 form2 = new Form2(szCookie);
            form2.Show();
        }

        private void button8_Click(object sender, EventArgs e)
        {
            if (!bThreadAttack)
            {
                bThreadAttack = true;
                AttackThread = new Thread(threadAttack);
                AttackThread.Start();
                button8.Text = "停止攻击";
            }
            else
            {
                bThreadAttack = false;
                Thread.Sleep(1000);
                AttackThread.Abort();
                button8.Text = "连续攻击";
            }
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            bxiap = checkBox1.Checked;
        }

        private void button9_Click(object sender, EventArgs e)
        {
            setbc();
            //             if (!bNoLimitedBC)
            //             {
            //                 bNoLimitedBC = true;
            //                 RigistThread = new Thread(ThreadRigist);
            //                 RigistThread.Start();
            //                 button9.Text = "停止";
            //             }
            //             else
            //             {
            //                 bNoLimitedBC = false;
            //                 Thread.Sleep(1000);
            //                 RigistThread.Abort();
            //                 button9.Text = "刷好友";
            //             }
        }

        private void checkBox2_CheckedChanged(object sender, EventArgs e)
        {
            bAutoChange = checkBox2.Checked;
        }
        private void threadBuy71()
        {
            button10.Enabled = false;
            try
            {
                iSellPrice = int.Parse(textBox4.Text);
            }
            catch (System.Exception ex)
            {

            }
            try
            {
                //buy(31, 30);
                while (true)
                {

                    string ulr = "http://" + szhostport + "/connect/web/event_mahjong_do?tile=500";
                    CookieCollection cookies = new CookieCollection();
                    Cookie c = new Cookie("S", szCookie);
                    c.Domain = szhost;
                    cookies.Add(c);
                    c = new Cookie("_ga", "GA1.2.2058947360.1373369155");
                    c.Domain = szhost;
                    cookies.Add(c);
                    IDictionary<string, string> parameters = new Dictionary<string, string>()
                    {
                        {"",""}
                    };
                    parameters.Clear();

                    XmlDocument xml = null;
                    try
                    {
                        xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);

                    }
                    catch (System.Exception ex)
                    {
                        /*return null;*/
                    }
                }
            }
            catch (System.Exception ex)
            {

            }
            button10.Enabled = true;
        }
        private void button10_Click(object sender, EventArgs e)
        {
//             Thread thread71 = new Thread(threadBuy71);
//             thread71.Start();
//             getGuidIFO();
//             GuildBattle(iGuildID, serial_id);

            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = szhost;
            cookies.Add(c);
            IDictionary<string, string> parameters = new Dictionary<string, string>()
                    {
                        {"",""}
                    };
            parameters.Clear();

            string ulr = "http://" + szhostport + "/connect/app/friend/add_friend?cyt=1";
            //while (true)
                try
                {
                    int iuser = int.Parse(textBox9.Text);
                    parameters.Clear();
                    parameters.Add("dialog", Encrypt("1", key12));
                    parameters.Add("user_id", Encrypt(iuser.ToString(), key12));
                    CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                    //break;
                }
                catch (System.Exception ex)
                {
                }

        }
        List<string> userlist = new List<string>();
        private void Form1_Load(object sender, EventArgs e)
        {

            userlist.Add("ayaseuz");
            userlist.Add("ayasuez161");
            userlist.Add("lllpla1");
            userlist.Add("lllpla2");
            userlist.Add("lllpla3");
            userlist.Add("lllpla4");
            userlist.Add("lllpla5");
            userlist.Add("lllpla6");
            userlist.Add("lllpla7");
            userlist.Add("lllpla8");
            userlist.Add("lllpla9");
            userlist.Add("13516610800");
            userlist.Add("85984");
            userlist.Add("85985");
            userlist.Add("85986");
            userlist.Add("85987");
            userlist.Add("85988");
            userlist.Add("85989");
            userlist.Add("85990");
            userlist.Add("85991");
            userlist.Add("85992");
            userlist.Add("85993");
            userlist.Add("85994");
            userlist.Add("85995");
            userlist.Add("85996");
            userlist.Add("85997");
            userlist.Add("85998");
            userlist.Add("85999");
            userlist.Add("coleka");
            userlist.Add("robin0857");
            userlist.Add("1047535054");
            userlist.Add("hanshang426");
            userlist.Add("hanshang742");
            userlist.Add("kuangsan963");
            userlist.Add("FATDN");
            userlist.Add("kasame");
            userlist.Add("hentaisama997");
            userlist.Add("cqfcry0305");
            userlist.Add("SherlockSSH");
            userlist.Add("montage");
            userlist.Add("blookingg");
            userlist.Add("fd72c1");
            userlist.Add("fd72c3");
            userlist.Add("fd72c4");
            userlist.Add("fd72c5");
            userlist.Add("fd72c6");
            userlist.Add("sola222");
            userlist.Add("xxooorange");
            userlist.Add("foreverlxy911");
            userlist.Add("aaaasr");
            userlist.Add("wsfwsf2013");
            userlist.Add("aaaauc");
            userlist.Add("wyc93112");
            userlist.Add("Akatsukinorin");
            userlist.Add("akatsuki1001");
            userlist.Add("akatsuki1003");
            userlist.Add("zeroriginals");
            userlist.Add("370546860");
            userlist.Add("a370546860");
            userlist.Add("b370546860");
            userlist.Add("c370546860");
            userlist.Add("d370546860");
            userlist.Add("342351775");
            userlist.Add("vanvillor");
            userlist.Add("dirXP0");
            userlist.Add("dirXP1");
            userlist.Add("dirXP3");
            userlist.Add("dirXP4");
            userlist.Add("dirXP5");
            userlist.Add("dirXP15");
            userlist.Add("dirXP17");
            userlist.Add("dirXP18");
            userlist.Add("dirXP19");
            userlist.Add("dirXP20");
            userlist.Add("dirXP21");
            userlist.Add("zhang9500");
            userlist.Add("x554337087");
            userlist.Add("Akatsuki1001");
            userlist.Add("Akatsuki1002");
            userlist.Add("Akatsuki1003");
            userlist.Add("Akatsuki1004");
            userlist.Add("Akatsuki1005");
            userlist.Add("Akatsuki1006");
            userlist.Add("Akatsuki1007");
            userlist.Add("Akatsuki1008");
            userlist.Add("Akatsuki1009");
            userlist.Add("Akatsuki1010");
            userlist.Add("akatsuki1002");
            userlist.Add("qnchong");
            userlist.Add("qnchong0");
            cardset = new CardSet();
            allcards = new cards();
            Rewardbox = new rewardbox();
            CardChose = new cardchose();
            Battles = new List<BattleLog>();
            textBoxLog.DataBindings.Add("Text", actionlog, "Text", false, DataSourceUpdateMode.OnPropertyChanged);
            //textBoxLog.DataBindings.Add("Text", logbind, "str", false, DataSourceUpdateMode.OnPropertyChanged);

            logbind.DataBindings.Add("str", actionlog, "Text", false, DataSourceUpdateMode.OnPropertyChanged);
            //listBox1.Items = Battles;
            dataGridView1.DataSource = cardset;
            dataGridView2.DataSource = allcards;
            dataGridView3.DataSource = Rewardbox;
            dataGridView4.DataSource = CardChose;
            dataGridView1.Columns[0].ReadOnly = false;
            for (int i = 0; i < dataGridView1.Columns.Count; i++)
            {
                dataGridView1.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
                if (i > 0) dataGridView1.Columns[i].ReadOnly = true;
                dataGridView1.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            }
            for (int i = 0; i < dataGridView2.Columns.Count; i++)
            {
                dataGridView2.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
                dataGridView2.Columns[i].ReadOnly = true;
                dataGridView2.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            }
            for (int i = 0; i < dataGridView3.Columns.Count; i++)
            {
                dataGridView3.Columns[i].ReadOnly = true;
                dataGridView3.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            }

            //             foreach (DataGridViewRow dgvr in dataGridView4.Rows)
            //             {
            //                 dgvr.Cells[1].ReadOnly = true;
            //             }
            for (int i = 0; i < dataGridView4.Columns.Count; i++)
            {
                dataGridView4.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                dataGridView4.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
            }
        }

        private void textBoxLog_TextChanged(object sender, EventArgs e)
        {
            textBoxLog.SelectionStart = textBoxLog.Text.Length;
            textBoxLog.ScrollToCaret();
        }

        private void dataGridView1_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0)
            {
                return;
            }
            carddeck cd = cardset.getdeck(e.RowIndex);
            actionlog.Text += "开始换卡:" + cd.name + "\r\n";
            ChangeCard(cd.ToString(), cd.getLeader());
        }

        private void button11_Click(object sender, EventArgs e)
        {
            cardset.AddDeck(getdeck());
        }

        private void button12_Click(object sender, EventArgs e)
        {
            int index = dataGridView1.SelectedCells[0].RowIndex;
            if (index < 0)
            {
                return;
            }
            cardset.UpdateDeck(getdeck(), index);
        }

        private void button13_Click(object sender, EventArgs e)
        {
            int index = dataGridView1.SelectedCells[0].RowIndex;
            if (index < 0)
            {
                return;
            }
            cardset.RemoveDeck(index);
        }

        private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            int ic = e.ColumnIndex;
            int ir = e.RowIndex;
            if (ic == 0)
            {
                carddeck cd = cardset.getdeck(ir);
                cd.name = cardset.Rows[ir][0].ToString();
                cardset.UpdateDeck(cd, ir);
            }
        }
        bool bAutojob = false;
        private void checkBox4_CheckedChanged(object sender, EventArgs e)
        {
            bAutojob = checkBox4.Checked;
        }

        private void button17_Click(object sender, EventArgs e)
        {
            allcards.update(cardlist, comboBox4.SelectedIndex + 1);
        }

        private void button14_Click(object sender, EventArgs e)
        {
            DataGridViewSelectedCellCollection cells = dataGridView2.SelectedCells;
            if (cells.Count < 1)
            {
                return;
            }
            int irownum = cells[0].RowIndex;
            string str = allcards.Rows[irownum][0].ToString();
            textBox8.Text = str;
            //string[] str = new string[cells.Count];
            //int i = 0;
            //foreach (DataGridViewCell cell in cells)
            //{
            //    int irownum = cell.RowIndex;
            //    str[i] = allcards.Rows[irownum][0].ToString();
            //    i++;
            //}
            //carddeck cd = new carddeck(str);
            //cardset.AddDeck(cd);
        }
        public void threadOpen()
        {
            button15.Enabled = false;
            IDictionary<string, string> parameters = new Dictionary<string, string>()
            {
                {"",""}
            };
            parameters.Clear();
            string ulr = "http://" + szhostport + "/connect/app/menu/rewardbox?cyt=1";
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = szhost;
            cookies.Add(c);
            XmlDocument xml = null;

            while (true)
            {
                try
                {
                    xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                    break;
                }
                catch (System.Exception ex)
                {
                    continue;
                }
            }
            if (xml != null&&xml.InnerText!="")
            {
                if (int.Parse(xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("code").InnerText) != 0)
                {
                }
                szCookie = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("session_id").InnerText;
                XmlNode node0 = null;

                XmlNodeList nodeboxs = null;
                try
                {
                    node0 = xml.SelectSingleNode("response").SelectSingleNode("body").SelectSingleNode("rewardbox_list");

                    nodeboxs = node0.SelectNodes("rewardbox");
                }
                catch (System.Exception ex)
                {
                    button15.Enabled = true;
                    return;
                }
                if (nodeboxs == null)
                {
                    button15.Enabled = true;
                    return;
                }
                //dataGridView3.ClearSelection();
                Rewardbox.update(nodeboxs);

            }


            button15.Enabled = true;
        }
        public void threadGet()
        {
            button16.Enabled = false;

            DataGridViewSelectedCellCollection cells = dataGridView3.SelectedCells;
            if (cells.Count < 1)
            {
                return;
            }
            string str = "";
            int i = 0;
            foreach (DataGridViewCell cell in cells)
            {
                if (i == 0) str += cell.Value.ToString();
                else str += "," + cell.Value.ToString();
                i++;
                if (i == 20)
                {
                    getRewardsNoSell(str);
                    i = 0;
                    str = "";
                }
            }
            if (str != "") getRewardsNoSell(str);
            button16.Enabled = true;
        }
        private void button15_Click(object sender, EventArgs e)
        {
            Thread td = new Thread(threadOpen);
            td.Start();
        }

        private void button16_Click(object sender, EventArgs e)
        {
            Thread td = new Thread(threadGet);
            td.Start();
        }
        public void threadsellselect()
        {
            button18.Enabled = false;

            DataGridViewSelectedCellCollection cells = dataGridView2.SelectedCells;
            if (cells.Count < 1)
            {
                return;
            }
            string str = "";
            int i = 0;
            foreach (DataGridViewCell cell in cells)
            {
                if (i == 0) str += cell.Value.ToString();
                else str += "," + cell.Value.ToString();
                i++;
                if (i == 30)
                {
                    sellcard(str);
                    i = 0;
                    str = "";
                }
            }
            if (str != "") sellcard(str);
            allcards.update(cardlist, comboBox4.SelectedIndex + 1);
            button18.Enabled = true;
        }
        private void button18_Click(object sender, EventArgs e)
        {

            Thread td = new Thread(threadsellselect);
            td.Start();
        }

        private void dataGridView4_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
        }

        private void dataGridView4_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            CardChose.saveconfig();
            cardc = CardChose.getDeckNum(lv);
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listBox1.Items != null && listBox1.Items.Count > 0 && listBox1.SelectedItem != null)
            {
                BattleLog bl = (BattleLog)listBox1.SelectedItem;

                textBox7.Text = bl.Value.ToString();
            }
        }

        private void dataGridView4_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void button19_Click(object sender, EventArgs e)
        {
            if (!bThreadEx)
            {
                bThreadEx = true;
                ExThread = new Thread(ThreadEX);
                ExThread.Start();
                button19.Text = "停止";
            }
            else
            {
                bThreadEx = false;
                Thread.Sleep(1000);
                ExThread.Abort();
                button19.Text = "挂机";
            }
        }

        private void dataGridView2_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                int index = e.RowIndex;
                if (index >= 0 && index < allcards.Rows.Count)
                {
                    pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
                    pictureBox1.Image = new Bitmap(@allcards.PngList[index]);

                }
            }
            catch (System.Exception ex)
            {
            	
            }
        }

        private void dataGridView2_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                int index = e.RowIndex;
                if (index >= 0 && index < allcards.Rows.Count)
                {
                    pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
                    pictureBox1.Image = new Bitmap(@allcards.PngList[index]);

                }
            }
            catch (System.Exception ex)
            {

            }
        }

        private void button21_Click(object sender, EventArgs e)
        {
            
            DataGridViewSelectedCellCollection cells = dataGridView2.SelectedCells;
            if (cells.Count < 1)
            {
                return;
            }
            foreach (DataGridViewCell cell in cells)
            {
                int irownum = cell.RowIndex;
                listBox2.Items.Add( allcards.Rows[irownum][0]);
            }        
        }

        private void button23_Click(object sender, EventArgs e)
        {

            if (listBox2.Items != null && listBox2.Items.Count > 0 && listBox2.SelectedItem != null)
            {
                listBox2.Items.Remove(listBox2.SelectedItem);

            }
        }

        private void button20_Click(object sender, EventArgs e)
        {
            if (listBox2.Items.Count < 1 )
            {
                return;
            }
            string[] str = new string[listBox2.Items.Count];
            int i = 0;
            foreach (object cell in listBox2.Items)
            {
                str[i] = cell.ToString();
                i++;
            }
            if (textBox8.Text != "")
            {
                carddeck cd = new carddeck(str, textBox8.Text);
                cardset.AddDeck(cd);
            }
            else
            {
                carddeck cd = new carddeck(str);
                cardset.AddDeck(cd);
            }
        }
        private void compound(string szbase, string dogfood)
        {
            
            IDictionary<string, string> parameters = new Dictionary<string, string>()
            {
                {"",""}
            };
            parameters.Clear();
            parameters.Add("add_serial_id", Encrypt(dogfood, key12));
            parameters.Add("base_serial_id", Encrypt(szbase, key12));
            string ulr = "http://" + szhostport + "/connect/app/compound/buildup/compound?cyt=1";
            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = szhost;
            cookies.Add(c);
            XmlDocument xml = null;

            while (true)
            {
                try
                {
                    xml = CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                    break;
                }
                catch (System.Exception ex)
                {
                    continue;
                }
            }
            if (xml != null&&xml.InnerText!="")
            {
                //                 if (int.Parse(xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("error").SelectSingleNode("code").InnerText) != 0)
                //                 {
                //                     return 0;
                //                 }

                szCookie = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("session_id").InnerText;
                XmlNode node0 = xml.SelectSingleNode("response").SelectSingleNode("header").SelectSingleNode("your_data");
                if (node0 == null)
                {
                    return;
                }
                XmlNodeList nodeCardlist = null;

                try
                {
                    nodeCardlist = node0.SelectSingleNode("owner_card_list").SelectNodes("user_card");

                    if (nodeCardlist != null)
                    {
                        cardlist = nodeCardlist;
                    }
                    foreach (XmlNode nodes in nodeCardlist)
                    {
                        string sid = nodes.SelectSingleNode("serial_id").InnerText;
                        if (sid == szbase)
                        {
                            int icardlv = int.Parse(nodes.SelectSingleNode("lv").InnerText);
                            int icardlvmax = int.Parse(nodes.SelectSingleNode("lv_max").InnerText);
                            int icardhp = int.Parse(nodes.SelectSingleNode("hp").InnerText);
                            int icardpower = int.Parse(nodes.SelectSingleNode("power").InnerText);
                            int iHolo = int.Parse(nodes.SelectSingleNode("holography").InnerText);
                            actionlog.Text += "合成成功：" + sid + " lv:" + icardlv + "/" + icardlvmax + " HP:" + icardhp + " ATK:" + icardpower + "\r\n";
                        }
                    }
                }
                catch (System.Exception ex)
                {

                }
            }
        }
        public void threadCompound()
        {
            button22.Enabled = false;

            if (listBox2.Items.Count < 1 || textBox8.Text == "")
            {
                return;
            }
            string str = "";
            int i = 0;
            foreach (object cell in listBox2.Items)
            {
                if (i == 0) str += cell.ToString();
                else str += "," + cell.ToString();
                i++;
                if (i == 30)
                {
                    compound(textBox8.Text, str);
                    i = 0;
                    str = "";
                }
            }
            if (str != "") compound(textBox8.Text, str);
            //dataGridView2.ClearSelection();
            allcards.update(cardlist, comboBox4.SelectedIndex + 1);
            listBox2.Items.Clear();
            button22.Enabled = true;
        }
        private void button22_Click(object sender, EventArgs e)
        {
            Thread td = new Thread(threadCompound);
            td.Start();
        }

        private void radioButton8_CheckedChanged(object sender, EventArgs e)
        {
            SwitchSever(0);

        }

        private void radioButton10_CheckedChanged(object sender, EventArgs e)
        {

            SwitchSever(1);

        }
        int iServer = 0;
        private void SwitchSever(int iType)
        {
            switch (iType)
            {
                case 1://国服
                    iServer = 1;
                    GetApple();
                    szhost = "game1-CBT.ma.sdo.com";
                    szhostport = "game1-CBT.ma.sdo.com:10001";
                    DefaultUserAgent = "Million/100 (c1lgt; c1lgt; 4.1.2) samsung/c1lgt/c1lgt:4.1.2/JZO54K/E210LKLJLL7:user/release-keys GooglePlay";
                    button4.Visible = false;
                    button7.Visible = false;
                    checkBox5.Visible = false;
                    checkBox3.Visible = false;
                    checkBox4.Visible = false;
                    comboBox2.Visible = false;
                    button24.Visible = true;
                    label5.Visible = false;
                    checkBox6.Visible = true;
                    checkBox7.Visible = true;
                    key0 = baseKey;
                    break;
                default:
                    iServer = 0;
                    GetApple();
                    key0 = baseKey + "0000000000000000";
                    DefaultUserAgent = "Million/235 (c1lgt; c1lgt; 4.1.2) samsung/c1lgt/c1lgt:4.1.2/JZO54K/E210LKLJME2:user/release-keys GooglePlay";
                    szhost = "web.million-arthurs.com";
                    szhostport = "web.million-arthurs.com";
                    comboBox2.Visible = true;
                    label5.Visible = true;
                    button4.Visible = true;
                    button7.Visible = true;
                    button9.Visible = true;
                    checkBox1.Visible = true;
                    checkBox5.Visible = true;
                    checkBox3.Visible = true;
                    checkBox4.Visible = true;
                    checkBox6.Visible = false;
                    checkBox7.Visible = false;
                    button24.Visible = false;
                    break;
            }
        }

        public int iMasterBossID { get; set; }

        public bool bExplore { get; set; }

        private void button24_Click(object sender, EventArgs e)
        {
            Thread td = new Thread(getFairyRewards);
            td.Start();
        }
        Thread tdgettickt;
        private void button25_Click(object sender, EventArgs e)
        {
            if (!bgetTickt)
            {
                bgetTickt = true;
                tdgettickt = new Thread(ThreadGetTickt);
                tdgettickt.Start();
                button25.Text = "停止取卷";
            }
            else
            {
                bgetTickt = false;
                Thread.Sleep(1000);
                tdgettickt.Abort();
                button25.Text = "连续取卷";
            }
        }

        private void button26_Click(object sender, EventArgs e)
        {

            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = szhost;
            cookies.Add(c);
            IDictionary<string, string> parameters = new Dictionary<string, string>()
                    {
                        {"",""}
                    };
            parameters.Clear();

            string ulr = "http://" + szhostport + "/connect/app/friend/approve_friend?cyt=1";
            //while (true)
            try
            {
                int iuser = int.Parse(textBox9.Text);
                parameters.Clear();
                parameters.Add("dialog", Encrypt("1", key12));
                parameters.Add("user_id", Encrypt(iuser.ToString(), key12));
                CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                //break;
            }
            catch (System.Exception ex)
            {
            }
        }

        private void button27_Click(object sender, EventArgs e)
        {

            CookieCollection cookies = new CookieCollection();
            Cookie c = new Cookie("S", szCookie);
            c.Domain = szhost;
            cookies.Add(c);
            IDictionary<string, string> parameters = new Dictionary<string, string>()
                    {
                        {"",""}
                    };
            parameters.Clear();

            string ulr = "http://" + szhostport + "/connect/app/friend/remove_friend?cyt=1";
            //while (true)
            try
            {
                int iuser = int.Parse(textBox9.Text);
                parameters.Clear();
                parameters.Add("dialog", Encrypt("1", key12));
                parameters.Add("user_id", Encrypt(iuser.ToString(), key12));
                CreatePostHttpResponse(ulr, parameters, (int?)50000, string.Empty, Encoding.Default, cookies);
                //break;
            }
            catch (System.Exception ex)
            {
            }
        }

        private void radioButton9_CheckedChanged(object sender, EventArgs e)
        {
            bDM = radioButton9.Checked;
        }

        private void checkBox5_CheckedChanged(object sender, EventArgs e)
        {

        }
        Thread NolimiteBcThread;
        List<int> olda;
        int ioldgood = 0;
        private void ThreadNolimitedBC()
        {
            
            while (bNoLimitedBC)
            {
                if (BC < 300 && igoodid != 0 && ioldgood != 0)
                {
                    //fairygood(attackers, igoodid);
                    //Thread.Sleep(1000);
                    //fairygood(olda, ioldgood);
                    Thread.Sleep(1000);
                }
                else
                {
                    Thread.Sleep(10000);
                }
            }
        }
        private void button28_Click(object sender, EventArgs e)
        {
            if (!bNoLimitedBC)
            {
                bNoLimitedBC = true;
                NolimiteBcThread = new Thread(ThreadNolimitedBC);
                NolimiteBcThread.Start();
                button28.Text = "停止";
            }
            else
            {
                bNoLimitedBC = false;
                Thread.Sleep(1000);
                NolimiteBcThread.Abort();
                button28.Text = "无限BC";
            }
        }
    }


    sealed class BingdingText :Control
    {
        private string  _str;

        [Localizable(true)]
        [Bindable(true)]
        public string str
        {
            get { return _str; }
            set
            {
                if (string.IsNullOrEmpty(value) && value == _str)
                    return;

                _str = value;
            }
        }
    }
    
    sealed class Log : INotifyPropertyChanged
    {
        private string _Text = string.Empty;
        public string Text
        {
            get { return _Text; }
            set
            {
                if (string.IsNullOrEmpty(value) && value == _Text)
                    return;

                _Text = value;
                NotifyPropertyChanged(() => Text);
            }
        }
        public event PropertyChangedEventHandler PropertyChanged;

        public void NotifyPropertyChanged<T>(Expression<Func<T>> property)
        {
            if (PropertyChanged == null)
                return;

            var memberExpression = property.Body as MemberExpression;
            if (memberExpression == null)
                return;

            PropertyChanged.Invoke(this, new PropertyChangedEventArgs(memberExpression.Member.Name));
        }
        private const string LogPath = @"action_log.txt";
        private StreamWriter log;
        public static readonly Log instance = new Log();
        private Log()
        {
            if (Properties.Settings.Default.whritelog) log = new StreamWriter(LogPath, true);
        }
        public void WriteInfo(string message)
        {
            //actionlog += message;
            if(Properties.Settings.Default.whritelog)WriteInfo("{0}", message);
        }
        public void WriteInfo(string format, params object[] obj)
        {
            if (Properties.Settings.Default.whritelog)
            {
                try
                {
                    log.WriteLine(string.Format("[{0}] {1}", System.DateTime.Now, string.Format(format, obj)));
                    log.Flush();
                }
                catch
                {
                    // Nothing to do
                }
            }
        }
    }
    public class playerrank : IComparable<playerrank>
    {
        public string name = "";
        public int point = 0;
        public int ilv = 0;
        public int irank = 0;
        public string logintime = "";
        public override string ToString()
        {
            return string.Format("{0}，等级：{1}，贡献：{2}，排名：{3}，最后登录：{4}\r\n", this.name, this.ilv, this.point, this.irank, this.logintime);
        }

        public int CompareTo(playerrank other)
        {
            if (other == null)
                return 1;
            int value = other.point - this.point ;
            if (value == 0)
                value = this.ilv - other.ilv;
            return value;
        }
    }

    public class cardlvsort : IComparable<cardlvsort>
    {
        public string iserialid = "";
        public int icardid = 0;
        public int ilv = 0;
        public int ilvmax = 0;
        public int iAtack = 0;
        public int iHp = 0;
        public override string ToString()
        {
            return iserialid;
        }

        public int CompareTo(cardlvsort other)
        {
            if (other == null)
                return 1;
            int value = other.ilv - this.ilv;
            if (value == 0)
                value = this.icardid - other.icardid;
            return value;
        }
    }
    public class cardidsort : IComparable<cardidsort>
    {
        public string iserialid = "";
        public int icardid = 0;
        public int ilv = 0;
        public int ilvmax = 0;
        public int iAtack = 0;
        public int iHp = 0;
        public override string ToString()
        {
            return iserialid;
        }

        public int CompareTo(cardidsort other)
        {
            if (other == null)
                return 1;
            int value = other.icardid - this.icardid;
            if (value == 0)
                value = this.ilv - other.ilv;
            return value;
        }
    }
    public class cardhpsort : IComparable<cardhpsort>
    {
        public string iserialid = "";
        public int icardid = 0;
        public int ilv = 0;
        public int ilvmax = 0;
        public int iAtack = 0;
        public int iHp = 0;
        public override string ToString()
        {
            return iserialid;
        }

        public int CompareTo(cardhpsort other)
        {
            if (other == null)
                return 1;
            int value = other.iHp - this.iHp;
            if (value == 0)
                value = this.icardid - other.icardid;
            return value;
        }
    }
    public class cardatsort : IComparable<cardatsort>
    {
        public string iserialid = "";
        public int icardid = 0;
        public int ilv = 0;
        public int ilvmax = 0;
        public int iAtack = 0;
        public int iHp = 0;
        public override string ToString()
        {
            return iserialid;
        }

        public int CompareTo(cardatsort other)
        {
            if (other == null)
                return 1;
            int value = other.iAtack - this.iAtack;
            if (value == 0)
                value = this.icardid - other.icardid;
            return value;
        }
    }
    public class cards : DataTable
    {
        public string DIR = "D:\\full_thumbnail_chara\\card_full_max\\";
        public List<string> PngList;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="Cards"></param>
        /// <param name="tpyesort">1:lv 2:id 3:hp 4:atk</param>
        public void update(XmlNodeList Cards,int tpyesort = 1)
        {
            Rows.Clear();
            PngList.Clear();
            switch (tpyesort)
            {
                case 1:
                    {
                        List<cardlvsort> cdlist = new List<cardlvsort>();
                        foreach (XmlNode node in Cards)
                        {
                            cardlvsort cd = new cardlvsort();
                            cd.iserialid = node.SelectSingleNode("serial_id").InnerText;
                            cd.ilv = int.Parse(node.SelectSingleNode("lv").InnerText);
                            cd.icardid = int.Parse(node.SelectSingleNode("master_card_id").InnerText);
                            cd.ilvmax = int.Parse(node.SelectSingleNode("lv_max").InnerText);
                            cd.iHp = int.Parse(node.SelectSingleNode("hp").InnerText);
                            cd.iAtack = int.Parse(node.SelectSingleNode("power").InnerText);
                            cdlist.Add(cd);
                        }
                        cdlist.Sort();
                        foreach (cardlvsort cd in cdlist)
                        {
                            string[] dr = new string[5];
                            dr[0] = cd.iserialid;
                            dr[1] = cd.icardid.ToString();
                            dr[2] = cd.ilv + "/" + cd.ilvmax;
                            dr[3] = cd.iHp.ToString();
                            dr[4] = cd.iAtack.ToString();
                            string newPng = DIR + "full_thumbnail_chara_" + (cd.icardid + 5000) + ".png";
                            PngList.Add(newPng);
                            Rows.Add(dr);
                        }
                    }
                    break;
                case 2:
                    {
                        List<cardidsort> cdlist = new List<cardidsort>();
                        foreach (XmlNode node in Cards)
                        {
                            cardidsort cd = new cardidsort();
                            cd.iserialid = node.SelectSingleNode("serial_id").InnerText;
                            cd.ilv = int.Parse(node.SelectSingleNode("lv").InnerText);
                            cd.icardid = int.Parse(node.SelectSingleNode("master_card_id").InnerText);
                            cd.ilvmax = int.Parse(node.SelectSingleNode("lv_max").InnerText);
                            cd.iHp = int.Parse(node.SelectSingleNode("hp").InnerText);
                            cd.iAtack = int.Parse(node.SelectSingleNode("power").InnerText);
                            cdlist.Add(cd);
                        }
                        cdlist.Sort();
                        foreach (cardidsort cd in cdlist)
                        {
                            string[] dr = new string[5];
                            dr[0] = cd.iserialid;
                            dr[1] = cd.icardid.ToString();
                            dr[2] = cd.ilv + "/" + cd.ilvmax;
                            dr[3] = cd.iHp.ToString();
                            dr[4] = cd.iAtack.ToString();
                            string newPng = DIR + "full_thumbnail_chara_" + (cd.icardid + 5000) + ".png";
                            PngList.Add(newPng);
                            Rows.Add(dr);
                        }
                    }
                    break;
                case 3:
                    {
                        List<cardhpsort> cdlist = new List<cardhpsort>();
                        foreach (XmlNode node in Cards)
                        {
                            cardhpsort cd = new cardhpsort();
                            cd.iserialid = node.SelectSingleNode("serial_id").InnerText;
                            cd.ilv = int.Parse(node.SelectSingleNode("lv").InnerText);
                            cd.icardid = int.Parse(node.SelectSingleNode("master_card_id").InnerText);
                            cd.ilvmax = int.Parse(node.SelectSingleNode("lv_max").InnerText);
                            cd.iHp = int.Parse(node.SelectSingleNode("hp").InnerText);
                            cd.iAtack = int.Parse(node.SelectSingleNode("power").InnerText);
                            cdlist.Add(cd);
                        }
                        cdlist.Sort();
                        foreach (cardhpsort cd in cdlist)
                        {
                            string[] dr = new string[5];
                            dr[0] = cd.iserialid;
                            dr[1] = cd.icardid.ToString();
                            dr[2] = cd.ilv + "/" + cd.ilvmax;
                            dr[3] = cd.iHp.ToString();
                            dr[4] = cd.iAtack.ToString();
                            string newPng = DIR + "full_thumbnail_chara_" + (cd.icardid + 5000) + ".png";
                            PngList.Add(newPng);
                            Rows.Add(dr);
                        }
                    }
                    break;
                case 4:
                    {
                        List<cardatsort> cdlist = new List<cardatsort>();
                        foreach (XmlNode node in Cards)
                        {
                            cardatsort cd = new cardatsort();
                            cd.iserialid = node.SelectSingleNode("serial_id").InnerText;
                            cd.ilv = int.Parse(node.SelectSingleNode("lv").InnerText);
                            cd.icardid = int.Parse(node.SelectSingleNode("master_card_id").InnerText);
                            cd.ilvmax = int.Parse(node.SelectSingleNode("lv_max").InnerText);
                            cd.iHp = int.Parse(node.SelectSingleNode("hp").InnerText);
                            cd.iAtack = int.Parse(node.SelectSingleNode("power").InnerText);
                            cdlist.Add(cd);
                        }
                        cdlist.Sort();
                        foreach (cardatsort cd in cdlist)
                        {
                            string[] dr = new string[5];
                            dr[0] = cd.iserialid;
                            dr[1] = cd.icardid.ToString();
                            dr[2] = cd.ilv + "/" + cd.ilvmax;
                            dr[3] = cd.iHp.ToString();
                            dr[4] = cd.iAtack.ToString();
                            string newPng = DIR + "full_thumbnail_chara_" + (cd.icardid + 5000) + ".png";
                            PngList.Add(newPng);
                            Rows.Add(dr);
                        }
                    }
                    break;
                default:
                    break;
            }
        }
        public cards()
        {
            PngList = new List<string>();
            this.Columns.Add("serialid");
            this.Columns.Add("cardid");
            this.Columns.Add("lv");
            this.Columns.Add("hp");
            this.Columns.Add("atk");
        }
    }
    public class rewardbox : DataTable
    {
        public void update(XmlNodeList box)
        {
            Rows.Clear();
            foreach (XmlNode node in box)
            {
                string[] str = new string[4];
                str[0] = node.SelectSingleNode("id").InnerText;
                int itype = int.Parse(node.SelectSingleNode("type").InnerText);
                str[3] = node.SelectSingleNode("content").InnerText;
                switch (itype)
                {
                    case 2:
                        str[1] = node.SelectSingleNode("title").InnerText + "(" + node.SelectSingleNode("get_num").InnerText + ")";
                        str[2] = "道具";
                        break;
                    case 3:
                        str[1] = node.SelectSingleNode("title").InnerText + "(" + node.SelectSingleNode("point").InnerText + ")";
                        str[2] = "gold";
                        break;
                    case 4:
                        str[1] = node.SelectSingleNode("title").InnerText + "(" + node.SelectSingleNode("point").InnerText + ")";
                        str[2] = "绊点";
                        break;
                    case 7:
                        string szBX = "";
                        int ibx = int.Parse(node.SelectSingleNode("treasure_box").SelectSingleNode("box_type").InnerText);
                        int num = int.Parse(node.SelectSingleNode("treasure_box").SelectSingleNode("get_num").InnerText);
                        switch (ibx)
                        {
                            case 10101:
                                szBX = "白金箱";
                                break;
                            case 10102:
                                szBX = "金箱";
                                break;
                            case 10103:
                                szBX = "银箱";
                                break;
                            case 10104:
                                szBX = "铜箱";
                                break;
                            case 10105:
                                szBX = "木箱";
                                break;
                        }
                        str[1] = szBX + "(" + num + ")";
                        str[2] = "箱子";
                        break;
                    default:
                        str[1] = node.SelectSingleNode("title").InnerText;
                        str[2] = itype.ToString();
                        break;
                }
                Rows.Add(str);
            }
        }
        public rewardbox()
        {
            Columns.Add("serial_id");
            Columns.Add("name");
            Columns.Add("type");
            Columns.Add("content");
            
        }
    }


    public class carddeck
    {
        private string deckstring;
        private string leaderstring;
        public List<int> cardids;
        public string name;
        public override string ToString()
        {
            return deckstring;
        }
        public string getLeader()
        {
            return leaderstring;
        }
        public carddeck(string[] dec, string leader = null)
        {
            int ilengh = dec.Length;
            string decstring = "";
            cardids = new List<int>();
            decstring = dec[0];
            try
            {
                cardids.Add(int.Parse(dec[0]));
            }
            catch (System.Exception ex)
            {

            }
            for (int i = 1; i < ilengh;i++ )
            {
                decstring += "," + dec[i];
                try
                {
                    cardids.Add(int.Parse(dec[i]));
                }
                catch (System.Exception ex)
                {

                }
            }
            for (int i = ilengh; i < 12;i++ )
            {
                decstring += ",empty";
            }

            if (leader == null)
            {
                List<int> tep = cardids;
                tep.Sort();
                leaderstring = tep[tep.Count - 1].ToString();
            }
            else
            {
                leaderstring = leader;
            }
            deckstring = decstring;
            name = "名無しカードセート";
        }
        public carddeck(string dec, string leader = null)
        {
            string[] cards = dec.Split(',');
            deckstring = dec;
            cardids = new List<int>();
            foreach (string card in cards)
            {
                if (card != "empty")
                {
                    try
                    {
                        cardids.Add(int.Parse(card));
                    }
                    catch (System.Exception ex)
                    {

                    }
                }
            }
            if (leader == null)
            {
                List<int> tep = cardids;
                tep.Sort();
                leaderstring = tep[tep.Count - 1].ToString();
            }
            else
            {
                leaderstring = leader;
            }
            name = "名無しカードセート";
        }
    }
    public class CardSet:DataTable
    {
        private List<carddeck> decklist;
        public void AddDeck(carddeck newdeck)
        {
            decklist.Add(newdeck);
            string[] dr = new string[15];
            dr[0] = newdeck.name;
            dr[1] = newdeck.cardids.Count.ToString();
            dr[2] = newdeck.getLeader();
            for (int j = 0; j < ((newdeck.cardids.Count > 12) ? 12 : newdeck.cardids.Count); j++)
            {
                dr[3 + j] = newdeck.cardids[j].ToString();
            }
            Rows.Add(dr);
            saveconfig();
        }
        public void UpdateDeck(carddeck newdeck, int index)
        {
            decklist[index] = newdeck;
            Rows[index][0] = newdeck.name; 
            Rows[index][1] = newdeck.cardids.Count.ToString();
            Rows[index][2] = newdeck.getLeader();
            for (int j = 0; j < 12; j++)
            {
                if (j < newdeck.cardids.Count) Rows[index][3 + j] = newdeck.cardids[j].ToString();
                else
                    Rows[index][3 + j] = "";
            }
            saveconfig();
        }
        public void RemoveDeck(int index)
        {
            Rows.RemoveAt(index);
            decklist.RemoveAt(index);
            saveconfig();
        }
        public carddeck getdeck(int index)
        {
            if (index < 0 || index > decklist.Count)
            {
                return null;
            }
            return decklist[index];
        }
        public CardSet()
        {
            this.Columns.Add("name");
            this.Columns.Add("cardsnum");
            this.Columns.Add("leader");
            this.Columns.Add("1-1");
            this.Columns.Add("1-2");
            this.Columns.Add("1-3");
            this.Columns.Add("2-1");
            this.Columns.Add("2-2");
            this.Columns.Add("2-3");
            this.Columns.Add("3-1");
            this.Columns.Add("3-2");
            this.Columns.Add("3-3");
            this.Columns.Add("4-1");
            this.Columns.Add("4-2");
            this.Columns.Add("4-3");
            decklist = new List<carddeck>();
            loadconfig();
        }
        private void loadconfig()
        {
            decklist.Clear();
            try
            {
                XmlDocument xml = new XmlDocument();
                xml.Load("cards.xml");
                if (xml.InnerXml != "")
                {
                    int num = int.Parse(xml.SelectSingleNode("cards").Attributes[0].InnerText);
                    for (int i = 0; i < num;i++ )
                    {
                        carddeck newdeck = new carddeck(xml.SelectSingleNode("cards").Attributes[i * 3 + 1].InnerText, xml.SelectSingleNode("cards").Attributes[i * 3 + 2].InnerText);
                        newdeck.name = xml.SelectSingleNode("cards").Attributes[i * 3 + 3].InnerText;
                        AddDeck(newdeck);
                    }
                }
                else
                {
                    saveconfig();
                }
            }
            catch (System.Exception ex)
            {
                saveconfig();
            }
        }
        public void saveconfig()
        {

            XmlTextWriter writer = new XmlTextWriter("cards.xml", Encoding.UTF8);

            //使用自动缩进便于阅读
            writer.Formatting = Formatting.Indented;

            // 书写版本为“1.0”的 XML 声明
            writer.WriteStartDocument();

            // 写注释
            writer.WriteComment("配置文件");

            //写入用户元素
            writer.WriteStartElement("cards");

            // 加入属性： type="IT"
            writer.WriteStartAttribute("nums");
            writer.WriteString(decklist.Count.ToString());
            writer.WriteEndAttribute();
            int i = 1;
            foreach (carddeck cd in decklist)
            {
                writer.WriteStartAttribute("deck" + i.ToString());
                writer.WriteString(cd.ToString());
                writer.WriteEndAttribute();

                writer.WriteStartAttribute( "leader" + i.ToString());
                writer.WriteString(cd.getLeader().ToString());
                writer.WriteEndAttribute();

                writer.WriteStartAttribute("name" + i.ToString());
                writer.WriteString(cd.name.ToString());
                writer.WriteEndAttribute();
                i++;
            }
            //关闭卡组元素，并书写结束标签
            writer.WriteEndElement();

            // 关闭任何打开的元素或属性
            writer.WriteEndDocument();

            //将XML写入文件并且关闭XmlTextWriter
            writer.Close();
        }
    }

    public class ComboBoxItem
    {
        private string _text = null;
        private object _value = null;
        public string Text { get { return this._text; } set { this._text = value; } }
        public object Value { get { return this._value; } set { this._value = value; } }
        public override string ToString()
        {
            return this._text;
        }
    }

    public class cardchose : DataTable
    {
        public int ifullcardnum { get; set; }
        public int ibase3cardnum { get; set; }
        public int isubcardnum { get; set; }
        public int iwolfmusumecardnum { get; set; }
        public int ifullcardcost { get; set; }
        public int ibase3cardcost { get; set; }
        public int isubcardcost { get; set; }
        public int iwolfmusumecardcost { get; set; }
        private List<cardsetnum> decklist;
        public class cardsetnum : IComparable<cardsetnum>
        {
            
            public int num { set; get; }
            public int limited { set; get; }
            public int cost { set; get; }

            public int CompareTo(cardsetnum other)
            {
                if (other == null)
                    return 1;
                int value = this.limited - other.limited;
                if (value == 0)
                    value = this.num - other.num;
                return value;
            }
            public cardsetnum(string snum,string slimited,string scost)
            {
                num = 0;
                limited = 0;
                try
                {
                    num = int.Parse(snum);
                }
                catch (System.Exception ex)
                {
                	
                }
                try
                {
                    limited = int.Parse(slimited);
                }
                catch (System.Exception ex)
                {

                }
                try
                {
                    cost = int.Parse(scost);
                }
                catch (System.Exception ex)
                {

                }
            }
        }
        public void AddDeck(cardsetnum newdeck)
        {
            string[] str= new string[3];
            str[0] = newdeck.num.ToString();
            str[1] = newdeck.limited.ToString();
            str[2] = newdeck.cost.ToString();
            Rows.Add(str);
            decklist.Add(newdeck);
        }
        private void loadconfig()
        {
            decklist.Clear();
            try
            {
                XmlDocument xml = new XmlDocument();
                xml.Load("cardschange.xml");
                if (xml.InnerXml != "")
                {
                    int num = int.Parse(xml.SelectSingleNode("cardschange").Attributes[0].InnerText);
                    ifullcardnum = int.Parse(xml.SelectSingleNode("cardschange").Attributes[1].InnerText);
                    ibase3cardnum = int.Parse(xml.SelectSingleNode("cardschange").Attributes[3].InnerText);
                    isubcardnum = int.Parse(xml.SelectSingleNode("cardschange").Attributes[5].InnerText);
                    iwolfmusumecardnum = int.Parse(xml.SelectSingleNode("cardschange").Attributes[7].InnerText);

                    ifullcardcost = int.Parse(xml.SelectSingleNode("cardschange").Attributes[2].InnerText);
                    ibase3cardcost = int.Parse(xml.SelectSingleNode("cardschange").Attributes[4].InnerText);
                    isubcardcost = int.Parse(xml.SelectSingleNode("cardschange").Attributes[6].InnerText);
                    iwolfmusumecardcost = int.Parse(xml.SelectSingleNode("cardschange").Attributes[8].InnerText);
                    string[] str = new string[3];
                    str[0] = ibase3cardnum.ToString();
                    str[1] = "点名";
                    str[2] = ibase3cardcost.ToString();
                    Rows.Add(str);
                    str[0] = ifullcardnum.ToString();
                    str[1] = "全卡";
                    str[2] = ifullcardcost.ToString();
                    Rows.Add(str);
                    str[0] = iwolfmusumecardnum.ToString();
                    str[1] = "狼娘";
                    str[2] = iwolfmusumecardcost.ToString();
                    Rows.Add(str);
                    str[0] = isubcardnum.ToString();
                    str[1] = "外敌";
                    str[2] = isubcardcost.ToString();
                    Rows.Add(str);
                    for (int i = 0; i < num; i++)
                    {
                        cardsetnum newdeck = new cardsetnum(xml.SelectSingleNode("cardschange").Attributes[i * 3 + 9].InnerText, xml.SelectSingleNode("cardschange").Attributes[i * 3 + 10].InnerText, xml.SelectSingleNode("cardschange").Attributes[i * 3 + 11].InnerText);
                        //newdeck.name = xml.SelectSingleNode("cards").Attributes[i * 3 + 3].InnerText;
                        AddDeck(newdeck);
                    }
                }
                else
                {
                    saveconfig();
                }
            }
            catch (System.Exception ex)
            {
                saveconfig();
            }
        }
        public void saveconfig()
        {
            try
            {
                ifullcardnum = (int)Rows[1][0];
                ibase3cardnum = (int)Rows[0][0];
                isubcardnum = (int)Rows[3][0];
                iwolfmusumecardnum = (int)Rows[2][0];

                ifullcardcost = (int)Rows[1][2];
                ibase3cardcost = (int)Rows[0][2];
                isubcardcost = (int)Rows[3][2];
                iwolfmusumecardcost = (int)Rows[2][2];

                decklist.Clear();
                for (int j = 4; j < Rows.Count; j++)
                {
                    cardsetnum csn = new cardsetnum(Rows[j][0].ToString(), Rows[j][1].ToString(), Rows[j][2].ToString());
                    decklist.Add(csn);
                }
                decklist.Sort();
            }
            catch (System.Exception ex)
            {
            	
            }
            XmlTextWriter writer = new XmlTextWriter("cardschange.xml", Encoding.UTF8);

            //使用自动缩进便于阅读
            writer.Formatting = Formatting.Indented;

            // 书写版本为“1.0”的 XML 声明
            writer.WriteStartDocument();

            // 写注释
            writer.WriteComment("配置文件");

            //写入用户元素
            writer.WriteStartElement("cardschange");

            // 加入属性： type="IT"
            writer.WriteStartAttribute("nums");
            writer.WriteString(decklist.Count.ToString());
            writer.WriteEndAttribute();
            writer.WriteStartAttribute("a0");
            writer.WriteString(ifullcardnum.ToString());
            writer.WriteEndAttribute();
            writer.WriteStartAttribute("b0");
            writer.WriteString(ifullcardcost.ToString());
            writer.WriteEndAttribute();
            writer.WriteStartAttribute("a1");
            writer.WriteString(ibase3cardnum.ToString());
            writer.WriteEndAttribute();
            writer.WriteStartAttribute("b1");
            writer.WriteString(ibase3cardcost.ToString());
            writer.WriteEndAttribute();
            writer.WriteStartAttribute("a2");
            writer.WriteString(isubcardnum.ToString());
            writer.WriteEndAttribute();
            writer.WriteStartAttribute("b2");
            writer.WriteString(isubcardcost.ToString());
            writer.WriteEndAttribute();
            writer.WriteStartAttribute("a3");
            writer.WriteString(iwolfmusumecardnum.ToString());
            writer.WriteEndAttribute();
            writer.WriteStartAttribute("b3");
            writer.WriteString(iwolfmusumecardcost.ToString());
            writer.WriteEndAttribute();
            int i = 1;
            foreach (cardsetnum cd in decklist)
            {
                writer.WriteStartAttribute("num" + i.ToString());
                writer.WriteString(cd.num.ToString());
                writer.WriteEndAttribute();

                writer.WriteStartAttribute("limited" + i.ToString());
                writer.WriteString(cd.limited.ToString());
                writer.WriteEndAttribute();

                writer.WriteStartAttribute("cost" + i.ToString());
                writer.WriteString(cd.cost.ToString());
                writer.WriteEndAttribute();
                i++;
            }
            //关闭卡组元素，并书写结束标签
            writer.WriteEndElement();

            // 关闭任何打开的元素或属性
            writer.WriteEndDocument();

            //将XML写入文件并且关闭XmlTextWriter
            writer.Close();
        }
        public cardchose()
        {
            decklist = new List<cardsetnum>();
            Columns.Add("卡组号");
            Columns[0].DataType = typeof(int);
            Columns.Add("≥");
            Columns.Add("cost");
            Columns[2].DataType = typeof(int);
            loadconfig();
        }
        public int[] getDeckNum(int iLv)
        {
            int[] ireturn = { ibase3cardnum ,ibase3cardcost};
            if (iLv > 9999)
            {
                ireturn = new int[2] { 0, 0 };
            }
            foreach (cardsetnum csn in decklist)
            {
                if (iLv > 9999)
                {
                    if (iLv <= csn.limited)
                    {
                        ireturn[0] = csn.num;
                        ireturn[1] = csn.cost;
                        break;
                    }
                }
                else if (iLv >= csn.limited)
                {
                    ireturn[0] = csn.num;
                    ireturn[1] = csn.cost;
                }
            }
            return ireturn;
        }
    }
    public class BattleTurn : Object
    {
        public List<XmlNode> Turnxml;
        public int turn { get; set; }
        public string EnemyName { get; set; }
        public int playerDamage { get; set; }
        public int SkillDamage { get; set; }
        public int SkillHeal { get; set; }
        public int superDamage { get; set; }
        public int EnemyDamega { get; set; }
        public int iskillcard { get; set; }
        public int iskillid { get; set; }
        public int playerHeal { get; set; }
        public int playerHpStart { get; set; }
        public int playerHpEnd { get; set; }
        public int enemyHpStart { get; set; }
        public int enemyHpEnd { get; set; }

        private string _str;
        public void Do()
        {
            foreach (XmlNode actionnode in Turnxml)
            {
                XmlNode supernode = actionnode.SelectSingleNode("special_attack_damage");
                XmlNode jobnode = actionnode.SelectSingleNode("battle_job_skill");
                XmlNode skillnode = actionnode.SelectSingleNode("skill_card");
                XmlNode damagenode = actionnode.SelectSingleNode("attack_damage");
                if (supernode != null)
                {
                    superDamage = int.Parse(supernode.InnerText);
                }
                else if (jobnode != null)
                {
                    XmlNode jobdamenode = jobnode.SelectSingleNode("enemy_damage");
                    XmlNode jobHpnode = jobnode.SelectSingleNode("player_up_hp");
                    if (jobdamenode != null)
                    {
                        SkillDamage = int.Parse(jobdamenode.InnerText);
                    }
                    if (jobHpnode != null)
                    {
                        SkillHeal = int.Parse(jobHpnode.InnerText);
                    }
                }
                else if (skillnode != null)
                {
                    iskillcard = int.Parse(skillnode.InnerText);
                    iskillid = int.Parse(actionnode.SelectSingleNode("skill_id").InnerText);
                    XmlNode skillhealnode = actionnode.SelectSingleNode("skill_hp_player");
                    if (skillhealnode != null)
                    {
                        playerHeal = int.Parse(skillhealnode.InnerText);
                    }
                }
                if (damagenode != null)
                {
                    if (actionnode.SelectSingleNode("action_player").InnerText == "0")
                    {
                        playerDamage += int.Parse(damagenode.InnerText);
                    }
                    else
                    {
                        EnemyDamega += int.Parse(damagenode.InnerText);
                    }
                }
            }
            _str = doString();
        }
        public override string ToString()
        {
            return _str;
        }
        private string doString()
        {
            string str = "回合" + turn + ":\r\n";
            playerHpEnd = playerHpStart;
            enemyHpEnd = enemyHpStart;
            if (superDamage!=0)
            {
                str += "你发动super，造成伤害：" + superDamage + "," + EnemyName + " HP" + enemyHpEnd + "→" + (enemyHpEnd -= superDamage) + "\r\n";
            }
            if (SkillDamage != 0)
            {
                str += "弓手怨念反弹伤害：" + SkillDamage + "," + EnemyName + " HP" + enemyHpEnd + "→" + (enemyHpEnd -= SkillDamage) + "\r\n";
            }
            if (SkillHeal != 0)
            {
                str += "风水发动治疗" + SkillHeal + ",HP" + playerHpEnd + "→" + (playerHpEnd += SkillHeal) + "\r\n";
            }
            if (iskillcard != 0)
            {
                str += "card" + iskillcard.ToString() + "发动技能" + iskillid.ToString() + "\r\n";
            }
            if (playerHeal != 0)
            {
                
                str += "治疗" + playerHeal + ",HP" + playerHpEnd + "→" + (playerHpEnd += playerHeal) + "\r\n";
            }
            str += "你发动攻击，造成伤害" + playerDamage + "," + EnemyName + " HP" + enemyHpEnd + "→" + (enemyHpEnd -= playerDamage) + "\r\n";

            str += EnemyName + "发动攻击造成伤害" + EnemyDamega + ",HP" + playerHpEnd + "→" + ((playerHpEnd -= EnemyDamega) < 0 ? (playerHpEnd = 0) : playerHpEnd) + "\r\n";
            return str;
        }
        public BattleTurn(int hp1,int hp2)
        {
            playerHpStart = hp1;
            enemyHpStart = hp2;
            playerDamage = 0;
            Turnxml = new List<XmlNode>();
        }
        public BattleTurn newTurn()
        {
            BattleTurn bt = new BattleTurn(playerHpEnd, enemyHpEnd);
            bt.EnemyName = EnemyName;
            return bt;
        }
    }
    public class Buff : Object
    {
        public string name { get; set; }
        public int type { get; set; }
        public string ccards { get; set; }
        public int hp { get; set; }
        public Buff(XmlNode actionnode)
        {
            name = actionnode.SelectSingleNode("combo_name").InnerText;
            ccards = actionnode.SelectSingleNode("combo_card_list_player").InnerText;
            type = int.Parse(actionnode.SelectSingleNode("combo_type").InnerText);
            hp = int.Parse(actionnode.SelectSingleNode("combo_hp_player").InnerText);
        }
        public override string ToString()
        {
            return type + "|" + name + "|" + ccards + "|" + hp +"\r\n";
        }
    }
    public class BattleLog : Object
    {
        public int EnemyLv { get; set; }
        public int HpContribution { get; set; }
        public int AtkContribution { get; set; }
        public int itemcount { get; set; }
        private string EnemyName;

        private int PlayerHP_Start;
        private int PlayerHP_Buffed;
        private int PlayerHP_Final;

        public List<Buff> combolist;
        private List<int> hpbufflist;
        private List<int> PlayerDamaglist;
        private List<int> PlayerHeallist;
        private List<int> EnemyDamagelist;
        private List<BattleTurn> TurnList;

        private int JobDamage;
        private int JobHp_up;
        private int JobDamageID;

        private int iTurn;

        private int SuperDamage;

        private int EnemyHP_Start;
        private int EnemyHP_MAX;
        private int EnemyHP_Final;

        private string _str;


        private string _text = null;
        private object _value = null;
        public string Text { get { return this._text; } set { this._text = value; } }
        public object Value { get { return this._value; } set { this._value = value; } }
        public override string ToString()
        {
            return this._text;
        }
        public BattleLog(XmlNode battlenode, int lv, int c1, int c2, string name = "")
        {
            EnemyLv = lv;
            HpContribution = c1;
            AtkContribution = c2;
            hpbufflist = new List<int>();
            PlayerDamaglist = new List<int>();
            EnemyDamagelist = new List<int>();
            PlayerHeallist = new List<int>();
            TurnList = new List<BattleTurn>();
            combolist = new List<Buff>();
            SuperDamage = 0;
            JobHp_up = 0;
            JobDamage = 0;

            XmlNodeList playerlist = battlenode.SelectNodes("battle_player_list");
            XmlNodeList actionlist = battlenode.SelectNodes("battle_action_list");



            PlayerHP_Start = int.Parse(playerlist[0].SelectSingleNode("hp").InnerText);
            EnemyHP_Start = int.Parse(playerlist[1].SelectSingleNode("hp").InnerText);
            EnemyHP_MAX = int.Parse(playerlist[1].SelectSingleNode("maxhp").InnerText);
            EnemyName = playerlist[1].SelectSingleNode("name").InnerText;
            int iturn = 0;
            BattleTurn bt = new BattleTurn(PlayerHP_Start, EnemyHP_Start);
            bt.EnemyName = EnemyName;
            foreach (XmlNode actionnode in actionlist)
            {
                XmlNode turnnode = actionnode.SelectSingleNode("turn");
                XmlNode exitnode = actionnode.SelectSingleNode("battle_exit");
                if (exitnode != null)
                {
                    if (exitnode.InnerText == "1")
                    {
                        break;
                    }
                }
                else if (turnnode != null)
                {
                    iturn = int.Parse(turnnode.InnerText);
                    if (iturn != 1)
                    {
                        bt.Do();
                        PlayerDamaglist.Add(bt.playerDamage);
                        EnemyDamagelist.Add(bt.EnemyDamega);
                        if (bt.playerHeal != 0) PlayerHeallist.Add(bt.playerHeal);
                        TurnList.Add(bt);
                        bt = bt.newTurn();
                        bt.turn = iturn;
                    }
                    else
                    {
                        bt.enemyHpStart = EnemyHP_Start - JobDamage;
                        PlayerHP_Buffed = PlayerHP_Start + hpbufflist.Sum() + JobHp_up;
                        bt.playerHpStart = PlayerHP_Buffed;
                        bt.turn = iturn;
                    }
                }
                else if (iturn == 0)
                {
                    XmlNode jobnode = actionnode.SelectSingleNode("battle_job_skill");
                    XmlNode combonode = actionnode.SelectSingleNode("combo_name");
                    if (jobnode != null)
                    {
                        XmlNode jobdamenode = jobnode.SelectSingleNode("enemy_damage");
                        XmlNode jobdhpupnode = jobnode.SelectSingleNode("player_up_hp");
                        if (jobdamenode != null)
                        {
                            JobDamage = int.Parse(jobdamenode.InnerText);
                            JobDamageID = int.Parse(jobnode.SelectSingleNode("job_skill_id").InnerText);
                        }
                        else if (jobdhpupnode != null)
                        {
                            JobHp_up = int.Parse(jobdhpupnode.InnerText);
                        }

                    }
                    else if (combonode != null)
                    {
                        Buff buff = new Buff(actionnode);
                        if (buff.hp != 0)
                        {
                            hpbufflist.Add(buff.hp);
                        }
                        combolist.Add(buff);
                    }
                }
                else
                {
                    XmlNode supernode = actionnode.SelectSingleNode("special_attack_damage");
                    if (supernode != null)
                    {
                        SuperDamage = int.Parse(supernode.InnerText);
                    }
                    bt.Turnxml.Add(actionnode);
                }
            }
            bt.Do();
            PlayerDamaglist.Add(bt.playerDamage);
            EnemyDamagelist.Add(bt.EnemyDamega);
            if (bt.playerHeal != 0) PlayerHeallist.Add(bt.playerHeal);
            PlayerHP_Final = bt.playerHpEnd;
            EnemyHP_Final = bt.enemyHpEnd;
            iTurn = bt.turn;
            TurnList.Add(bt);
            _str = EnemyName + " lv" + EnemyLv + " HP:" + EnemyHP_Start + "/" + EnemyHP_MAX + "\r\n\r\n";
            _str += "发动combo：\r\n";
            foreach (Buff buff in combolist)
            {
                _str += buff.ToString();
            }
            if (JobHp_up != 0)
            {
                _str += "弓手buff HP " + JobHp_up + "上升\r\n";
            }
            _str += "HP:" + PlayerHP_Start + "→" + PlayerHP_Buffed;
            _str += "\r\n";
            _str += "职业技能ID:" + JobDamageID + "发动，造成伤害" + JobDamage + "," + EnemyName + " HP" + EnemyHP_Start + "→" + (EnemyHP_Start - JobDamage) + "\r\n\r\n";
            foreach (BattleTurn turn in TurnList)
            {
                _str += turn.ToString();
            }
            _str += "\r\n";
            _str += "你总共造成伤害：" + (EnemyHP_Start - EnemyHP_Final) + " 攻击贡献：" + AtkContribution + ",剩余hp:" + PlayerHP_Final + "/" + PlayerHP_Buffed + " 残血贡献：" + HpContribution + "\r\n";
            if (itemcount != 0)
            {
                _str += "获得收集道具：" + itemcount;
            }
            _value = _str;
            if (AtkContribution == 0)
            {
                _text = name + ":" + EnemyName + " lv" + EnemyLv + " 道具：" + HpContribution;
            }
            else
                _text = "外敌：" + EnemyName + " lv" + EnemyLv + " 残血贡献：" + HpContribution + " 攻击贡献：" + AtkContribution;
        }
    }


}
